package com.yanqu.road.server.manger.union;

import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.activity.seacraft.pirateriot.config.SeacraftPirateRiotConfig;
import com.yanqu.road.entity.enums.activity.eActivityCookBoyType;
import com.yanqu.road.entity.log.cross.*;
import com.yanqu.road.entity.servercenter.ServerInfo;
import com.yanqu.road.entity.task.args.OreWarActivityUnionRiseRankArgs;
import com.yanqu.road.entity.task.args.RelationActivityUnionRiseRankArgs;
import com.yanqu.road.entity.task.args.union.UnionActivityTaskArgs;
import com.yanqu.road.entity.tradewar.UserTradeWarInfo;
import com.yanqu.road.logic.bussiness.player.*;
import com.yanqu.road.logic.bussiness.union.UnionBussiness;
import com.yanqu.road.logic.helper.ActivityHelper;
import com.yanqu.road.pb.assistant.AssistantProto;
import com.yanqu.road.server.gameplayer.module.activity.tomb.TombMgr;
import com.yanqu.road.server.gameplayer.module.union.UnionParergonModule;
import com.yanqu.road.server.manger.*;
import com.yanqu.road.server.manger.activity.*;
import com.yanqu.road.server.manger.activity.bowart.BowArtMgr;
import com.yanqu.road.server.manger.activity.douluodalu.DouLuoDaLuMgr;
import com.yanqu.road.server.manger.activity.dragonboatrace.DragonBoatRaceMgr;
import com.yanqu.road.server.manger.activity.fivehero.FiveHeroMgr;
import com.yanqu.road.server.manger.activity.ghost.GhostMgr;
import com.yanqu.road.server.manger.activity.hanghai.HangHaiMgr;
import com.yanqu.road.server.manger.activity.orewar.OreWarActivityMgr;
import com.yanqu.road.server.manger.activity.orewar.OreWarActivityRankMgr;
import com.yanqu.road.server.manger.activity.peakstronghold.PeakStrongholdActivityMgr;
import com.yanqu.road.server.manger.activity.rankunionwar.RankUnionWarMgr;
import com.yanqu.road.server.manger.activity.seacraft.SeacraftSouthSeaMgr;
import com.yanqu.road.server.manger.activity.seacraft.SeacraftPirateRiotMgr;
import com.yanqu.road.server.manger.activity.tonbing.TonBingMgr;
import com.yanqu.road.server.manger.activity.tonbingchannel.ChannelTonBingMgr;
import com.yanqu.road.server.manger.activity.tongbing.TongBingMgr;
import com.yanqu.road.server.manger.activity.twins.TwinsMgr;
import com.yanqu.road.server.manger.activity.unionwar.UnionPhaseWarMgr;
import com.yanqu.road.server.manger.assistant.AssistantMgr;
import com.yanqu.road.server.manger.beautyescort.BeautyEscortMgr;
import com.yanqu.road.server.manger.log.AutoLogMgr;
import com.yanqu.road.server.manger.monopolymarket.MonopolyMarketMgr;
import com.yanqu.road.server.manger.player.TradeWarMgr;
import com.yanqu.road.server.manger.activity.orewar.OreWarMgr;
import com.yanqu.road.server.pb.UnionPb;
import com.yanqu.road.logic.config.GameConfig;
import com.yanqu.road.entity.activity.ActivityConditionInfo;
import com.yanqu.road.entity.activity.UserActivityConditionData;
import com.yanqu.road.entity.activity.dafuweng.DFWConfig;
import com.yanqu.road.entity.enums.*;
import com.yanqu.road.entity.player.UserInfo;
import com.yanqu.road.entity.player.UserPatrons;
import com.yanqu.road.entity.task.args.CommonActivityUnionRiseRankArgs;
import com.yanqu.road.entity.task.args.UnionRiseRankArgs;
import com.yanqu.road.entity.task.args.union.UnionRechargeUserArgs;
import com.yanqu.road.entity.union.*;
import com.yanqu.road.pb.union.UnionProto;
import com.yanqu.road.pb.worldmessage.WorldMessageProto;
import com.yanqu.road.server.GameServer;
import com.yanqu.road.server.TempMgr;
import com.yanqu.road.server.TempServer;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.activity.strongholdwar.StrongholdModule;
import com.yanqu.road.server.gameplayer.module.player.*;
import com.yanqu.road.server.gameplayer.module.union.UnionModule;
import com.yanqu.road.server.logic.mail.MailManager;
import com.yanqu.road.server.manger.activity.dafuweng.DaFuWengMgr;
import com.yanqu.road.server.manger.activity.strongholdwar.StrongholdActivityMgr;
import com.yanqu.road.server.manger.activity.strongholdwar.StrongholdActivityRankMgr;
import com.yanqu.road.server.manger.config.GoodsMgr;
import com.yanqu.road.server.manger.config.UnionConfigMgr;
import com.yanqu.road.server.manger.player.UserMgr;
import com.yanqu.road.server.manger.player.WorldMessageMgr;
import com.yanqu.road.server.manger.player.GamePlayerMgr;
import com.yanqu.road.server.manger.rank.RankMgr;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.utils.LocalDateTimeHelper;
import com.yanqu.road.utils.RandomHelper;
import com.yanqu.road.utils.date.DateHelper;
import com.yanqu.road.utils.property.Property;
import com.yanqu.road.utils.property.PropertyHelper;
import com.yanqu.road.utils.string.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.math.BigInteger;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;

public class UnionMgr extends TempMgr {

    private static Logger logger = LogManager.getLogger(UnionMgr.class.getName());

    private static final Object lockObj = new Object();

    private static RandomHelper random = new RandomHelper();

    private static Map<String, UnionInfo> unionInfoMap;

    private static Map<String, UnionInfo> deleteUnionInfoMap;

    private static Map<String, Map<Long, UnionMember>> unionMemberMap;

    private static Map<Long, UnionMember> deleteUnionMemberMap;

    private static AtomicLong maxUnionAliasId;

    private static Map<String, Map<Integer, UnionFlag>> unionFlagMap;

    public static Object getLockObj() {
        return lockObj;
    }

    public static void readUnionFlag(String unionUid) {
        Map<Integer, UnionFlag> flagMap = unionFlagMap.get(unionUid);
        if (flagMap == null) {
            return;
        }
        for (UnionFlag flag : new ArrayList<>(flagMap.values())) {
            flag.setRead(true);
        }
    }

    public static Map<String, UnionInfo> getDeleteUnionInfoMap() {
        return deleteUnionInfoMap;
    }

    public static Map<String, UnionInfo> getUnionInfoMap() {
        return unionInfoMap;
    }

    public static int changeApplyTitle(GamePlayer player, int title) {
        String unionUid = player.getUserInfo().getUnionUid();
        if(StringUtils.isNullOrEmpty(unionUid)){
            return GameErrorCode.E_UNION_NO_JOIN_UNION;
        }
        UnionMember member = UnionMgr.getUnionMember(unionUid, player.getUserId());
        if(null == member){
            return GameErrorCode.E_UNION_NO_JOIN_UNION;
        }
        if (member.getPosition() != eUnionPosition.Master.getValue() && member.getPosition() != eUnionPosition.DeputyMaster.getValue()) {
                return GameErrorCode.E_UNION_POSITION_NO_ENOUGH;
        }
        int minTitle = UnionConfigMgr.getMinApplyTitle();
        int maxTitle = UnionConfigMgr.getMaxApplyTitle();
        if (title != 0 && (title < minTitle || title > maxTitle)) {
            return GameErrorCode.E_UNION_APPLY_TITLE_NO_IN_RANGE;
        }
        UnionInfo unionInfo = getUnionInfo(unionUid);
        synchronized (getLockObj()) {
            unionInfo.setApplyTitleLimit(title);
        }
        notifyAllMemberUnionInfo(unionUid, 0);
        return 0;
    }

    @Override
    public boolean init() throws Exception {
        return reload();
    }

    @Override
    public boolean reloadConfig() throws Exception {
        return true;
    }

    @Override
    public boolean stop() {
        return false;
    }

    @Override
    public boolean save() {
        List<UnionInfo> unionInfoList = new ArrayList<>(unionInfoMap.values());
        for (UnionInfo unionInfo : unionInfoList) {
            if (unionInfo.isInsertOption()) {
                UnionBussiness.addUnionInfo(unionInfo);
            } else if (unionInfo.isUpdateOption()) {
                UnionBussiness.updateUnionInfo(unionInfo);
            }
        }
        List<UnionMember> tempDeleteMemberList = new ArrayList<>(deleteUnionMemberMap.values());
        for (UnionMember unionMember : tempDeleteMemberList) {
            if (unionMember.isInsertOption()) {
                UnionBussiness.addUnionMember(unionMember);
            } else if (unionMember.isUpdateOption()) {
                UnionBussiness.updateUnionMember(unionMember);
            }
        }
        for (Map.Entry<String, Map<Long, UnionMember>> dateEntry : unionMemberMap.entrySet()) {
            for (UnionMember unionMember : dateEntry.getValue().values()) {
                if (unionMember.isInsertOption()) {
                    UnionBussiness.addUnionMember(unionMember);
                } else if (unionMember.isUpdateOption()) {
                    UnionBussiness.updateUnionMember(unionMember);
                }
            }
        }
        for (Map<Integer, UnionFlag> flagMap : new ArrayList<>(unionFlagMap.values())) {
            for (UnionFlag flag : new ArrayList<>(flagMap.values())) {
                if (flag.isInsertOption()) {
                    UnionBussiness.addUnionFlag(flag);
                } else if (flag.isUpdateOption()) {
                    UnionBussiness.updateUnionFlag(flag);

                }
            }
        }


        return true;
    }

    @Override
    public boolean reloadData() {
        initMaxUnionAliasId();
        Map<String, UnionInfo> tempUnionInfoMap = new ConcurrentHashMap<>();
        Map<String, UnionInfo> tempDeleteUnionInfoMap = new ConcurrentHashMap<>();
        UnionBussiness.getUnionInfoMap(tempUnionInfoMap, tempDeleteUnionInfoMap);
        unionInfoMap = tempUnionInfoMap;
        deleteUnionInfoMap = tempDeleteUnionInfoMap;
        Map<String, Map<Long, UnionMember>> tempUnionMemberMap = new ConcurrentHashMap<>();
        Map<Long, UnionMember> tempDeleteMemberMap = new ConcurrentHashMap<>();
        UnionBussiness.getUnionMemberMap(tempUnionMemberMap, tempDeleteMemberMap);
        unionMemberMap = tempUnionMemberMap;
        deleteUnionMemberMap = tempDeleteMemberMap;
        unionFlagMap = UnionBussiness.getAllUnionFlag();
        //校验商会有效性
        checkUnionValid();
        resetOneDay();
        //checkUnionApplyTitleLimit();
        return true;
    }

    private void checkUnionApplyTitleLimit() {
        int minApplyTitle = UnionConfigMgr.getMinApplyTitle();
        int maxApplyTitle = UnionConfigMgr.getMaxApplyTitle();
        for (UnionInfo info : new ArrayList<>(unionInfoMap.values())) {
            if (info.getApplyTitleLimit() < minApplyTitle) {
                info.setApplyTitleLimit(minApplyTitle);
            } else if (info.getApplyTitleLimit() > maxApplyTitle) {
                info.setApplyTitleLimit(maxApplyTitle);
            }
        }
    }

    /**
     * 初始化读取当前最大商会别名编号
     */
    private static void initMaxUnionAliasId() {
        long tempMaxUnionAliasId = UnionBussiness.getMaxUnionAliasId();
        if (0 == tempMaxUnionAliasId) {
            String serverIdStr = String.valueOf(GameServer.getInstance().getServerId());
            String unionAliasIdStr = serverIdStr.substring(5);
            unionAliasIdStr = "1" + unionAliasIdStr;
            while (unionAliasIdStr.length() < 9) {
                unionAliasIdStr += 0;
            }
            maxUnionAliasId = new AtomicLong(Long.valueOf(unionAliasIdStr));
        } else {
            maxUnionAliasId = new AtomicLong(tempMaxUnionAliasId);
        }
    }

    /**
     * 获取下一个商会别名编号
     */
    public static long getNextUnionAliasId() {
        return maxUnionAliasId.incrementAndGet();
    }

    /**
     * 商会数据校验
     */
    private static void checkUnionValid() {
        for (UnionInfo unionInfo : unionInfoMap.values()) {
            Map<Long, UnionMember> memberMap = unionMemberMap.get(unionInfo.getUnionUid());
            if (null == memberMap) {//没有成员
                unionInfo.setDelete(true);
            }
        }
        List<String> unionUidList = new ArrayList<>();
        for (Map.Entry<String, Map<Long, UnionMember>> dataEntry : unionMemberMap.entrySet()) {
            if (!unionInfoMap.containsKey(dataEntry.getKey())) {
                unionUidList.add(dataEntry.getKey());
            }
        }
        for (String unionUid : unionUidList) {
            Map<Long, UnionMember> memberMap = unionMemberMap.remove(unionUid);
            if (null != memberMap) {
                for (UnionMember member : memberMap.values()) {
                    member.setUnionUid("");
                    deleteUnionMemberMap.put(member.getUserId(), member);
                }
            }
        }
    }

    /**
     * 创建联盟
     */
    public static int createUnion(GamePlayer player, String unionName, boolean isAllowRandomJoin, String outNotice, String wechatCode,
                                  String qqCode, String innerNotice, int unionFlag, String unionUid) {
        UnionInfo unionInfo;
        synchronized (lockObj) {
            //商会重名检测
            if (UnionMgr.checkUnionNameSame(unionName)) {
                return GameErrorCode.E_UNION_NAME_SAME;
            }
            AttributeModule attributeModule = player.getModule(AttributeModule.class);
            int freeCreateUnionTimes = (int) attributeModule.getAttribute(ePlayerAttrType.FreeCreateUnionTimes);
            if (player.getUserInfo().getVipExp() <= 0 || freeCreateUnionTimes >= GameConfig.UNION_FREE_CREATE_TIMES) {//没有充值的或者大于免费创建次数就需要消耗元宝
                if (!player.getModule(CurrencyModule.class).removeCurrency(new Property(GameConfig.GAME_MONEY_INGOTS, BigInteger.valueOf(GameConfig.UNION_CREATE_INGOTS_COST)),
                        eLogMoneyType.Union, eLogMoneyType.UnionCreate)) {
                    return GameErrorCode.E_BAG_INGOTS_NO_ENOUGH;
                }
            } else {
                attributeModule.addAttribute(ePlayerAttrType.FreeCreateUnionTimes, 1);   //增加免费创建商会次数
            }
            unionInfo = initUnionInfo(player, unionName, isAllowRandomJoin, outNotice, wechatCode, qqCode, innerNotice, unionFlag, unionUid);
            try {
                //玩家加入商会要结算他在盐场没冠名的奖励
                OreWarMgr.sendUnionNamingJoinQuitReward(unionInfo.getUnionUid(), player.getUserId());
            } catch (Exception e) {
                logger.error("createUnion", e);
            }
            createUnionMember(unionInfo, player.getUserInfo(), eUnionPosition.Master.getValue());
            UnionNoticeMgr.checkUnionNotice(unionInfo.getUnionUid());

            //同步商会副业
            player.getModule(UnionParergonModule.class).loginSendMsg();
        }

        player.sendPacket(Protocol.U_UNION_DETAIL, UnionMgr.getUnionDetailMsg(unionInfo.getUnionUid(), eUnionSyncType.CreateUnion.getValue()));
        notifyUnionMemberCount(unionInfo);
        RankMgr.changeUnionRank(unionInfo);
        notifySameNicknameCount(unionInfo);

        try {
            //实时更新榜单上的用户的家族信息
            OreWarActivityRankMgr.changeUserInfo(player.getUserId());
            //有人退出刷新下商会坑位状态，因为冠名可能会改变
            OreWarMgr.refreshOreStation();
            //跨服刷新带上用户基础信息，用来判断变化的冠名
            List<Long> userIdList = new ArrayList<>();
            userIdList.add(player.getUserId());
            OreWarMgr.refreshCrossOreStation(userIdList);
            BeautyEscortMgr.createUnion(unionInfo, player.getUserId());
        } catch (Exception e) {
            logger.error("createUnion", e);
        }
        //DataAnalyticsMgr.trackUnionCreateGuild(player,unionInfo);
        return 0;
    }

    public static int modifyUnion(GamePlayer player, int type, String content) {
        String unionUid = player.getUserInfo().getUnionUid();
        if (StringUtils.isNullOrEmpty(unionUid)) {
            return GameErrorCode.E_UNION_NO_JOIN_UNION;
        }
        UnionInfo unionInfo = getUnionInfo(unionUid);
        if (null == unionInfo) {
            return GameErrorCode.E_UNION_NO_JOIN_UNION;
        }
        int ret;
        if (0 == type) {//商会名
            ret = UnionConfigMgr.checkUnionName(content, unionUid, player);
        } else if (1 == type) {//微信号
            ret = UnionConfigMgr.checkWechatCode(content);
        } else if (2 == type) {//qq号
            ret = UnionConfigMgr.checkQqCode(content);
        } else if (3 == type) {//对外公告
            ret = UnionConfigMgr.checkOutNotice(content, unionUid, player);
        } else if (4 == type) {//对内公告
            ret = UnionConfigMgr.checkInnerNotice(content);
        } else {
            ret = GameErrorCode.E_UNION_MODIFY_TYPE_ERROR;
        }
        if (0 != ret) {
            return ret;
        }

        boolean isResetNoticeReadState = false;
        if (0 == type) {
            synchronized (lockObj) {
                if (!Objects.equals(content, unionInfo.getUnionName())) {
                    if (checkUnionNameSame(content)) {
                        return GameErrorCode.E_UNION_NAME_SAME;
                    }

                    //改名需要消耗元宝
                    if (!player.getModule(CurrencyModule.class).removeCurrency(new Property(GameConfig.GAME_MONEY_INGOTS, BigInteger.valueOf(GameConfig.UNION_CHANGE_NAME_COST)),
                            eLogMoneyType.Union, eLogMoneyType.UnionChangeName)) {
                        return GameErrorCode.E_BAG_INGOTS_NO_ENOUGH;
                    }
                }
                unionInfo.setUnionName(content);
                MonopolyMarketMgr.changeUnionName(unionUid,content);
            }
        } else if (1 == type) {//微信号
            synchronized (unionInfo) {
                unionInfo.setWechatCode(content);
            }
        } else if (2 == type) {//qq号
            synchronized (unionInfo) {
                unionInfo.setQqCode(content);
            }
        } else if (3 == type) {//对外公告
            synchronized (unionInfo) {
                unionInfo.setOutNotice(content);
            }
        } else if (4 == type) {//对内公告
            synchronized (unionInfo) {
                if (!Objects.equals(content, unionInfo.getInnerNotice())) {//重新设置商会公告
                    isResetNoticeReadState = true;
                }
                unionInfo.setInnerNotice(content);
            }
        }

        if (isResetNoticeReadState) {//重置状态并通知所有成员
            Map<Long, UnionMember> memberMap = getUnionMemberMap(unionUid);
            if (null != memberMap) {
                for (UnionMember member : memberMap.values()) {
                    if (member.getUserId() == player.getUserId()) {
                        member.setNoticeReadState(eUnionNoticeReadState.Read.getValue());
                    } else {
                        member.setNoticeReadState(eUnionNoticeReadState.Default.getValue());
                    }
                }
            }
            notifyAllMemberUnionInfo(unionUid, 0);
        }
//            UnionActivityMgr.changeUnionActivityValue(unionInfo);
        //增加联盟日志
        UnionNoticeMgr.addNotice(player, unionUid, eUnionNoticeType.UnionModify.getValue(), "");
        RankMgr.changeUnionRank(unionInfo);
        return 0;
    }

    public static int quitUnion(GamePlayer player) {
        String unionUid = player.getUserInfo().getUnionUid();
        if (StringUtils.isNullOrEmpty(unionUid)) {
            return GameErrorCode.E_UNION_NO_JOIN_UNION;
        }
        if (!StrongholdActivityMgr.isGameFinish()) {
            return GameErrorCode.E_STRONGHOLD_CAN_NOT_QUIT;
        }
        if(!SeacraftSouthSeaMgr.canInAndOutUnion(unionUid)){
            return GameErrorCode.E_SEACRAFT_SOUTH_SEA_ACTIVITY_CAN_NOT_QUIT;
        }
        if (!SeacraftPirateRiotMgr.canOperateUnion()) {
            return GameErrorCode.E_SEACRAFT_PIRATE_RIOT_CAN_NOT_QUIT_UNION;
        }
        if (!TongBingMgr.canChangeUnion()) {
            return GameErrorCode.E_TONG_BING_CAN_NOT_QUIT_UNION;
        }
        if (!TonBingMgr.canChangeUnion()) {
            return GameErrorCode.E_TON_BING_CAN_NOT_QUIT_UNION;
        }
        if (!ChannelTonBingMgr.canChangeUnion()) {
            return GameErrorCode.E_CTON_BING_CAN_NOT_QUIT_UNION;
        }
        if (!FiveHeroMgr.canChangeUnion()) {
            return GameErrorCode.E_FIVE_HERO_CAN_NOT_QUIT_UNION;
        }
        // 大航海商会限制
        if (!HangHaiMgr.canChangeUnion()) {
            return GameErrorCode.E_HANGHAI_ACTIVITY_CAN_NOT_QUIT_UNION;
        }

        if (!PeakStrongholdActivityMgr.canChangeUnion(unionUid)) {
            return GameErrorCode.E_PEAK_HOLD_CAN_NOT_QUIT_UNION;
        }

        ActivityInfo activityInfo = TradeWarActivityMgr.getInTimeActivityInfo();
        if (null != activityInfo) {//跨服商战进行时不能退出商会
            return GameErrorCode.E_UNION_CROSS_TRADE_WAR_CAN_NO_QUIT;
        }
        if (!TombMgr.canChangeUnion()){
            return GameErrorCode.E_TOMB_ACTIVITY_CAN_NO_QUIT;
        }
        UnionInfo unionInfo;
        UnionTradeMgr.syncRouteCanJoinToMember(unionUid, player.getUserId());   //商贸红点
        synchronized (lockObj) {
            unionInfo = getUnionInfo(unionUid);
            if (null == unionInfo) {
                return GameErrorCode.E_UNION_NO_JOIN_UNION;
            }
            if (player.getUserId() == unionInfo.getMasterUserId()) {
                return GameErrorCode.E_UNION_MASTER_CAN_NO_QUIT;
            }
            try {
                //玩家退出商会要结算他在盐场冠名的奖励
                OreWarMgr.sendUnionNamingJoinQuitReward(unionUid, player.getUserId());
            } catch (Exception e) {
                logger.error("quitUnion", e);
            }
            removeFormUnion(null, unionInfo, player.getUserId(), eUnionSyncType.QuitUnion.getValue());
            player.sendPacket(Protocol.U_UNION_DETAIL, getUnionDetailMsg(unionUid, eUnionSyncType.QuitUnion.getValue()));
        }
        //增加联盟日志
        UnionNoticeMgr.addNotice(player, unionUid, eUnionNoticeType.QuitUnion.getValue(), "");
        player.notifyListener(eGamePlayerEventType.UnionMemberCount.getValue(), 0);
        notifyAllMemberUnionInfo(unionUid, player.getUserId());
        notifyUnionMemberCount(unionInfo);
        notifySameNicknameCount(unionInfo);
        try {
            //有人退出刷新下商会坑位状态，因为冠名可能会改变
            OreWarMgr.refreshOreStation();
            //跨服刷新带上用户基础信息，用来判断变化的冠名
            List<Long> userIdList = new ArrayList<>();
            userIdList.add(player.getUserId());
            OreWarMgr.refreshCrossOreStation(userIdList);
            //商会战活动
            UnionPhaseWarMgr.quitUnion(player.getUserId(), unionInfo);
            //走镖
            BeautyEscortMgr.quitUnion(player.getUserId(), unionInfo);
            DouLuoDaLuMgr.unionChange(player);
            AssistantMgr.clearUnionMallSet(player.getUserId());
        } catch (Exception e) {
            logger.error("quitUnion", e);
        }
        // [大富翁]刷新下商会加成
        DaFuWengMgr.notifyEmptyUnionData(Collections.singletonList(player.getUserId()), unionUid);
        ArrayList<Long> memberList = new ArrayList<>(getUnionMemberMap(unionUid).keySet());
        memberList.add(player.getUserId());
        DaFuWengMgr.unionMemberChange(memberList);
        //退出日志
        AutoLogMgr.add(new LogUnionMemberChange(player.getUserId(), unionUid, ""));
        return 0;
    }

    public static int kickPlayer(GamePlayer player, long kickUserId) {
        ActivityInfo activityInfo = TradeWarActivityMgr.getInTimeActivityInfo();
        String unionUid = player.getUserInfo().getUnionUid();
        if (null != activityInfo) {//跨服商战进行时不能踢玩家出商会
            return GameErrorCode.E_UNION_CROSS_TRADE_WAR_CAN_NO_KICK;
        }

        if (!StrongholdActivityMgr.isGameFinish()) {
            return GameErrorCode.E_STRONGHOLD_CAN_NOT_KICK;
        }
        //巅峰据点战
        if (!PeakStrongholdActivityMgr.canChangeUnion(unionUid)) {
            return GameErrorCode.E_PEAK_HOLD_CAN_NOT_KICK_UNION;
        }
        if(!SeacraftSouthSeaMgr.canInAndOutUnion(unionUid)){
            return GameErrorCode.E_SEACRAFT_SOUTH_SEA_ACTIVITY_CAN_NOT_KICK;
        }
        if (!SeacraftPirateRiotMgr.canOperateUnion()) {
            return GameErrorCode.E_SEACRAFT_PIRATE_RIOT_CAN_NOT_KICK_UNION;
        }
        if (!TongBingMgr.canChangeUnion()) {
            return GameErrorCode.E_TONG_BING_CAN_NOT_KICK_UNION;
        }
        if (!TonBingMgr.canChangeUnion()) {
            return GameErrorCode.E_TON_BING_CAN_NOT_KICK_UNION;
        }
        if (!ChannelTonBingMgr.canChangeUnion()) {
            return GameErrorCode.E_CTON_BING_CAN_NOT_KICK_UNION;
        }
        if (!FiveHeroMgr.canChangeUnion()) {
            return GameErrorCode.E_FIVE_HERO_CAN_NOT_KICK_UNION;
        }
        // 大航海商会限制
        if (!HangHaiMgr.canChangeUnion()) {
            return GameErrorCode.E_HANGHAI_ACTIVITY_CAN_NOT_KICK_UNION;
        }
        if(!RankUnionWarMgr.canKickUnion(unionUid)){
            return GameErrorCode.E_RANKUNIONWAR_ACTIVITY_CAN_NOT_KICK;
        }
        if (!TombMgr.canChangeUnion()){
            return GameErrorCode.E_TOMB_ACTIVITY_CAN_NO_KICK;
        }
        int result;
        UnionInfo unionInfo;
        UnionTradeMgr.syncRouteCanJoinToMember(unionUid, kickUserId);   //商贸红点
        synchronized (lockObj) {
            unionInfo = getUnionInfo(unionUid);
            try {
                //玩家退出商会要结算他在盐场冠名的奖励
                OreWarMgr.sendUnionNamingJoinQuitReward(unionUid, kickUserId);
            } catch (Exception e) {
                logger.error("kickPlayer", e);
            }
            result = removeFormUnion(player, unionInfo, kickUserId, eUnionSyncType.BeKick.getValue());
            if (0 != result) {
                return result;
            }
            player.sendPacket(Protocol.U_UNION_DETAIL, getUnionDetailMsg(unionUid, eUnionSyncType.Normal.getValue()));
        }
        //增加联盟日志
        UserInfo kickUserInfo = UserMgr.getUserInfo(kickUserId);
        UnionNoticeMgr.addNotice(player, unionUid, eUnionNoticeType.KickMember.getValue(), kickUserInfo.getNickName());
        notifyUnionMemberCount(unionInfo);
        GamePlayer kickPlayer = GamePlayerMgr.getOnlinePlayer(kickUserId);
        if (null != kickPlayer) {
            kickPlayer.notifyListener(eGamePlayerEventType.UnionMemberCount.getValue(), 0);
        }
        notifyAllMemberUnionInfo(unionUid, kickUserId);
        try {
            //有人退出刷新下商会坑位状态，因为冠名可能会改变
            OreWarMgr.refreshOreStation();
            //跨服刷新带上用户基础信息，用来判断变化的冠名
            List<Long> userIdList = new ArrayList<>();
            userIdList.add(kickUserId);
            OreWarMgr.refreshCrossOreStation(userIdList);

            // [大富翁]刷新下商会加成
            DaFuWengMgr.notifyEmptyUnionData(Collections.singletonList(kickUserId), unionUid);
            ArrayList<Long> memberList = new ArrayList<>(getUnionMemberMap(unionUid).keySet());
            memberList.add(kickUserId);
            DaFuWengMgr.unionMemberChange(memberList);

            UnionPhaseWarMgr.kickPlayer(unionInfo, kickUserId);
            DouLuoDaLuMgr.unionChange(kickUserId);
            BeautyEscortMgr.kickPlayer(unionInfo, kickUserId);
            AssistantMgr.clearUnionMallSet(kickUserId);

        } catch (Exception e) {
            logger.error("kickPlayer", e);
        }
        //退出日志
        AutoLogMgr.add(new LogUnionMemberChange(kickUserId, unionUid, ""));
        return 0;
    }


    public static int deleteUnion(GamePlayer player) {
        ActivityInfo activityInfo = TradeWarActivityMgr.getInTimeActivityInfo();
        String unionUid = player.getUserInfo().getUnionUid();
        if (null != activityInfo) {//跨服商战进行时不能解散商会
            return GameErrorCode.E_UNION_CROSS_TRADE_WAR_CAN_NO_DELETE;
        }
        if (!StrongholdActivityMgr.isGameFinish()) {
            return GameErrorCode.E_STRONGHOLD_CAN_NOT_DELETE;
        }
        //巅峰据点战
        if (!PeakStrongholdActivityMgr.canChangeUnion(unionUid)) {
            return GameErrorCode.E_PEAK_HOLD_CAN_NOT_DELETE_UNION;
        }
        if (!SeacraftPirateRiotMgr.canOperateUnion()) {
            return GameErrorCode.E_SEACRAFT_PIRATE_RIOT_CAN_NOT_DELETE_UNION;
        }
        if (!TongBingMgr.canChangeUnion()) {
            return GameErrorCode.E_TONG_BING_CAN_NOT_DELETE_UNION;
        }
        if (!TonBingMgr.canChangeUnion()) {
            return GameErrorCode.E_TON_BING_CAN_NOT_DELETE_UNION;
        }
        if (!ChannelTonBingMgr.canChangeUnion()) {
            return GameErrorCode.E_CTON_BING_CAN_NOT_DELETE_UNION;
        }
        if (!FiveHeroMgr.canChangeUnion()) {
            return GameErrorCode.E_FIVE_HERO_CAN_NOT_DELETE_UNION;
        }
        // 大航海商会限制
        if (!HangHaiMgr.canChangeUnion()) {
            return GameErrorCode.E_HANGHAI_ACTIVITY_CAN_NOT_DELETE_UNION;
        }
        if(!SeacraftSouthSeaMgr.canInAndOutUnion(unionUid)){
            return GameErrorCode.E_SEACRAFT_SOUTH_SEA_ACTIVITY_DELETE;
        }
        if(!UnionPhaseWarMgr.canDeleteUnion(unionUid)){
            return GameErrorCode.E_UNION_WAR_ACTIVITY_CAN_NO_DELETE;
        }
        if(!RankUnionWarMgr.canDelUnion(unionUid)){
            return GameErrorCode.E_RANKUNIONWAR_ACTIVITY_DELETE;
        }
        if (!TombMgr.canChangeUnion()){
            return GameErrorCode.E_TOMB_ACTIVITY_CAN_NO_DELETE;
        }
        UnionInfo unionInfo = getUnionInfo(unionUid);
        List<Long> syncUserIdList = new ArrayList<>();
        UnionTradeMgr.syncRouteCanJoinToMember(unionUid);   //商贸红点
        synchronized (lockObj) {
            unionInfo.setDelete(true);
            unionInfo.setRankAddExp(0L);
            Map<Long, UnionMember> memberMap = getUnionMemberMap(unionUid);
            if (null != memberMap) {
                try {
                    //解散发放冠名奖励
                    OreWarMgr.sendUnionDismissNamingChangeReward(unionUid);
                } catch (Exception e) {
                    logger.error("deleteUnion", e);
                }
                for (UnionMember unionMember : memberMap.values()) {
                    removeFormUnion(player, unionInfo, unionMember.getUserId(), eUnionSyncType.DeleteUnion.getValue());
                    syncUserIdList.add(unionMember.getUserId());
                }
            }
        }
        //榜单移除
        RankMgr.removeUnionRank(unionUid);
        notifyUnionActivityDeleteRank(player, unionUid);
        UnionTradeMgr.notifyUnionDelete(unionUid);//结束商贸
        for (long tempUserId : syncUserIdList) {
            GamePlayer tempPlayer = GamePlayerMgr.getOnlinePlayer(tempUserId);
            if (null != tempPlayer) {
                tempPlayer.notifyListener(eGamePlayerEventType.UnionMemberCount.getValue(), 0);
            }
            try {
                //实时更新榜单上的用户的家族信息
                OreWarActivityRankMgr.changeUserInfo(tempUserId);
                AssistantMgr.clearUnionMallSet(tempUserId);
            } catch (Exception e) {
                logger.error("deleteUnion", e);
            }
        }
        try {
            //有人退出刷新下商会坑位状态，因为冠名可能会改变
            OreWarMgr.refreshOreStation();
            //跨服刷新带上用户基础信息，用来判断变化的冠名
            OreWarMgr.refreshCrossOreStation(syncUserIdList);
            DouLuoDaLuMgr.unionChange(syncUserIdList);
        } catch (Exception e) {
            logger.error("deleteUnion", e);
        }
        try {
            DaFuWengMgr.notifyEmptyUnionData(syncUserIdList, unionUid);
            DaFuWengMgr.unionMemberChange(syncUserIdList);
        } catch (Exception e) {
            logger.error("deleteUnion", e);
        }
        try {
            BeautyEscortMgr.deleteUnion(syncUserIdList, unionInfo);
        } catch (Exception e){
            logger.error("BeautyEscortMgr.deleteUnion error!", e);
        }
        MonopolyMarketMgr.deleteUnion(syncUserIdList, unionUid);

        AutoLogMgr.add(new LogUnionDelete(player.getUserId(), unionUid, unionInfo.getMasterUserId(), unionInfo.getExperience(), unionInfo.getWealth(), 0));
        //DataAnalyticsMgr.trackUnionBreakGuild(player,unionInfo);
        return 0;
    }

    public static void notifyUnionActivityDeleteRank(GamePlayer player, String unionUid) {
        if(null != player) {
            player.notifyListener(eGamePlayerEventType.UnionExpRiseRank.getValue(), new UnionRiseRankArgs(UnionRiseRankArgs.NOTIFY_TYPE_DELETE, BigInteger.ZERO, unionUid));
            player.notifyListener(eGamePlayerEventType.UnionIntimacyRiseRank.getValue(), new UnionRiseRankArgs(UnionRiseRankArgs.NOTIFY_TYPE_DELETE, BigInteger.ZERO, unionUid));
            player.notifyListener(eGamePlayerEventType.UnionTradeWarScoreRiseRank.getValue(), new UnionRiseRankArgs(UnionRiseRankArgs.NOTIFY_TYPE_DELETE, BigInteger.ZERO, unionUid));
            player.notifyListener(eGamePlayerEventType.UnionAbilityRiseRank.getValue(), new UnionRiseRankArgs(UnionRiseRankArgs.NOTIFY_TYPE_DELETE, BigInteger.ZERO, unionUid));
            player.notifyListener(eGamePlayerEventType.UnionEarnSpeedRiseRank.getValue(), new UnionRiseRankArgs(UnionRiseRankArgs.NOTIFY_TYPE_DELETE, BigInteger.ZERO, unionUid));
            player.notifyListener(eGamePlayerEventType.OreWarAcCoinOutPut.getValue(), new UnionRiseRankArgs(UnionRiseRankArgs.NOTIFY_TYPE_DELETE, BigInteger.ZERO, unionUid));
            player.notifyListener(eGamePlayerEventType.CrossOreWarAcCoinOutPut.getValue(), new UnionRiseRankArgs(UnionRiseRankArgs.NOTIFY_TYPE_DELETE, BigInteger.ZERO, unionUid));
            player.notifyListener(eGamePlayerEventType.DaFuWengUnionScoreRank.getValue(), new UnionRiseRankArgs(UnionRiseRankArgs.NOTIFY_TYPE_DELETE, BigInteger.ZERO, unionUid));
            player.notifyListener(eGamePlayerEventType.DaFuWengUnionDamageRank.getValue(), new UnionRiseRankArgs(UnionRiseRankArgs.NOTIFY_TYPE_DELETE, BigInteger.ZERO, unionUid));
            player.notifyListener(eGamePlayerEventType.BowArtActivityUnionScoreRank.getValue(), new UnionRiseRankArgs(UnionRiseRankArgs.NOTIFY_TYPE_DELETE, BigInteger.ZERO, unionUid));
            player.notifyListener(eGamePlayerEventType.BowArtActivityUnionScoreCrossRank.getValue(), new UnionRiseRankArgs(UnionRiseRankArgs.NOTIFY_TYPE_DELETE, BigInteger.ZERO, unionUid));
            player.notifyListener(eGamePlayerEventType.GhostUnionScoreRank.getValue(), new UnionRiseRankArgs(UnionRiseRankArgs.NOTIFY_TYPE_DELETE, BigInteger.ZERO, unionUid));
            player.notifyListener(eGamePlayerEventType.DragonBoatRaceActivityUnionScoreRank.getValue(), new UnionRiseRankArgs(UnionRiseRankArgs.NOTIFY_TYPE_DELETE, BigInteger.ZERO, unionUid));
            player.notifyListener(eGamePlayerEventType.DragonBoatRaceActivityUnionScoreCrossRank.getValue(), new UnionRiseRankArgs(UnionRiseRankArgs.NOTIFY_TYPE_DELETE, BigInteger.ZERO, unionUid));
            player.notifyListener(eGamePlayerEventType.CookBoy1IntegralUserCrossRank.getValue(), new UnionRiseRankArgs(UnionRiseRankArgs.NOTIFY_TYPE_DELETE, BigInteger.ZERO, unionUid));
            player.notifyListener(eGamePlayerEventType.SeacraftPirateRiotUnionScoreRank.getValue(), new UnionRiseRankArgs(UnionRiseRankArgs.NOTIFY_TYPE_DELETE, BigInteger.ZERO, unionUid));
            List<ActivityInfo> dataList = CommonActivityMgr.getInTimeCommonActivityInfoList(eActivityType.CommonActivity.getValue());
            for (ActivityInfo activityInfo : dataList) {
                player.notifyListener(eGamePlayerEventType.CommonActivityScoreRiseRank.getValue(), new CommonActivityUnionRiseRankArgs(UnionRiseRankArgs.NOTIFY_TYPE_DELETE, BigInteger.ZERO, unionUid, activityInfo.getChildType()));
            }
        }
        TongBingMgr.unionChange(unionUid);
        TonBingMgr.unionChange(unionUid);
        ChannelTonBingMgr.unionChange(unionUid);
    }

    public static int setMemberPosition(GamePlayer player, long operateUserId, int position, boolean isBackend) {
        String unionUid = player.getUserInfo().getUnionUid();
        if (StringUtils.isNullOrEmpty(unionUid)) {
            return GameErrorCode.E_UNION_NO_JOIN_UNION;
        }
        UnionInfo unionInfo = getUnionInfo(unionUid);
        if (null == unionInfo) {
            return GameErrorCode.E_UNION_NO_JOIN_UNION;
        }
        synchronized (unionInfo) {
            UnionMember operateMember = getUnionMember(unionUid, operateUserId);
            if (null == operateMember) {
                return GameErrorCode.E_UNION_MEMBER_NO_FOUND;
            }
            if (!isBackend && !UnionConfigMgr.isContributionEnough(operateMember.getTotalContribution(), position)) {
                return GameErrorCode.E_UNION_CONTRIBUTION_NOT_ENOUGH;
            }
            // 转让族长
            UnionMember member = UnionMgr.getUnionMember(unionUid, player.getUserId());
            int oldOperatePosition = operateMember.getPosition();
            if (position == eUnionPosition.Master.getValue()) {
                if (member.getPosition() == eUnionPosition.Master.getValue()) {
                    operateMember.setPosition(position);
                    member.setPosition(eUnionPosition.Member.getValue());

                    unionInfo.setDecoration(operateMember.getUserBaseInfo().getDecoration());
                    unionInfo.setVipExp(operateMember.getUserBaseInfo().getVipExp());
                    unionInfo.setMasterNickName(operateMember.getUserBaseInfo().getNickName());
                    unionInfo.setMasterUserId(operateMember.getUserId());
                    //商会冲榜
                    notifyUnionActivityMasterChange(player.getUserId(), unionUid);
                    notifyUnionActivityMasterChange(operateUserId, unionUid);
                    //增加联盟日志
                    UnionNoticeMgr.addNotice(player, unionUid, eUnionNoticeType.ChangeMaster.getValue(), operateMember.getUserBaseInfo().getNickName());

                    //变更商会信息
                    RankMgr.changeUnionRank(unionInfo);
                    UnionActivityMgr.changeUnionInfo(unionInfo);
                    AutoLogMgr.add(new LogUnionChangeMaster(unionUid, false, player.getUserId(), operateUserId));

                    UnionPhaseWarMgr.memberPositionChange(unionInfo, player.getUserId(), eUnionPosition.Member.getValue());
                    BeautyEscortMgr.memberPositionChange(unionInfo, player.getUserId(), eUnionPosition.Member.getValue());
                } else {
                    return GameErrorCode.E_UNION_POSITION_NO_ENOUGH;
                }
            } else {
                // 判断当前职位个数
                if (UnionConfigMgr.isPositionCountMax(unionInfo, getUnionMemberMap(unionUid), position)) {
                    return GameErrorCode.E_UNION_POSITION_COUNT_FULL;
                }
                // 族长副族长不能被设置职位
                if (operateMember.getPosition() == eUnionPosition.Master.getValue()) {
                    return GameErrorCode.E_UNION_POSITION_NO_ENOUGH;
                }
                // 副族长只能被族长设置职位
                if (operateMember.getPosition() == eUnionPosition.DeputyMaster.getValue()) {
                    if (member.getPosition() != eUnionPosition.Master.getValue()) {
                        return GameErrorCode.E_UNION_POSITION_NO_ENOUGH;
                    }
                }
                operateMember.setPosition(position);
                //变更职位
                notifyUnionActivityMemberPositionChange(operateUserId, unionUid);

//                CrossUnionFightMgr.updateUserPosition(unionId, operateMember.getUserId(), operateMember.getPosition());
                //增加联盟日志
                UnionNoticeMgr.addNotice(player, unionUid, eUnionNoticeType.ChangePosition.getValue(), operateMember.getUserBaseInfo().getNickName(), String.valueOf(position));
            }
            player.sendPacket(Protocol.U_UNION_DETAIL, getUnionDetailMsg(unionUid, eUnionSyncType.Normal.getValue()));
            //同步商会信息给成员
            notifyAllMemberUnionInfo(unionUid, player.getUserId());
            UnionPhaseWarMgr.memberPositionChange(unionInfo, operateUserId, position);
            BeautyEscortMgr.memberPositionChange(unionInfo, operateUserId, position);
            //如果职位由普通变成管理，需要下发申请列表
            if ((position == eUnionPosition.Master.getValue() || position == eUnionPosition.DeputyMaster.getValue()) &&
                    (oldOperatePosition != eUnionPosition.Master.getValue() && oldOperatePosition != eUnionPosition.DeputyMaster.getValue())) {
                GamePlayer operatePlayer = GamePlayerMgr.getOnlinePlayer(operateUserId);
                if (null != operatePlayer) {
                    UnionJoinApplyMgr.sendJoinApplyList(operatePlayer, unionUid);
                }
            }
        }
        return 0;
    }


    private static void notifyUnionActivityMemberPositionChange(long userId, String unionUid) {
        try {
            //商会冲榜
            List<ActivityInfo> activityInfoList = NormalActivityMgr.getUnionRiseRankActivityList();
            for (ActivityInfo activityInfo : activityInfoList) {
                UnionActivityMgr.changeUnionActivityValue(activityInfo.getActivityId(), unionUid, userId, null, UnionRiseRankArgs.NOTIFY_TYPE_POSITION_CHANGE);
            }
            //万能
            List<ActivityInfo> commonActivityInfoList = CommonActivityMgr.getInTimeCommonActivityInfoList(eActivityType.CommonActivity.getValue());
            for (ActivityInfo activityInfo : commonActivityInfoList) {
                CommonActivityRankMgr.changeUnionActivityValue(activityInfo.getActivityId(), unionUid, userId, null, UnionRiseRankArgs.NOTIFY_TYPE_POSITION_CHANGE);
            }
            //盐场
            List<ActivityInfo> oreActivityInfoList = OreWarActivityMgr.getOpenActivityInfoList();
            for (ActivityInfo activityInfo : oreActivityInfoList) {
                if (ActivityMgr.activityInTime(activityInfo)) {
                    OreWarActivityRankMgr.changeUnionActivityValue(activityInfo.getActivityId(), unionUid, userId, null, UnionRiseRankArgs.NOTIFY_TYPE_POSITION_CHANGE);
                }
            }
            //商战
            ActivityInfo tradeWarActivityInfo = TradeWarActivityMgr.getInTimeActivityInfo();
            if (tradeWarActivityInfo != null) {
                UserActivityConditionData userActivityConditionData = null;
                List<ActivityConditionInfo> activityConditionInfoList = TradeWarActivityMgr.getActivityConditionInfoList(tradeWarActivityInfo.getActivityId(), TradeWarActivityMgr.CONDITION_TYPE_UNION);
                if (null != activityConditionInfoList && activityConditionInfoList.size() > 0) {
                    List<UserActivityConditionData> conditionDataList = UserTradeWarActivityBussiness.getUserActivityConditionDataList(tradeWarActivityInfo.getActivityId(), userId, TradeWarActivityMgr.CONDITION_TYPE_UNION);
                    for (UserActivityConditionData conditionData : conditionDataList) {
                        ActivityConditionInfo conditionInfo = TradeWarActivityMgr.getActivityConditionInfo(tradeWarActivityInfo.getActivityId(), conditionData.getConditionId());
                        if (conditionInfo.getType() == TradeWarActivityMgr.CONDITION_TYPE_UNION) {
                            userActivityConditionData = conditionData;
                            break;
                        }
                    }
                    if (null == userActivityConditionData) {
                        userActivityConditionData = NormalActivityMgr.initUserActivityConditionData(userId, UserMgr.getNickName(userId), BigInteger.ZERO,
                                tradeWarActivityInfo.getActivityId(), activityConditionInfoList.get(0).getConditionId(), activityConditionInfoList.get(0).getType());
                        UserTradeWarActivityBussiness.addUserActivityConditionData(userActivityConditionData);
                    }
                }

                TradeWarActivityRankMgr.changeUnionActivityValue(tradeWarActivityInfo.getActivityId(), unionUid, userId, userActivityConditionData, UnionRiseRankArgs.NOTIFY_TYPE_POSITION_CHANGE);
            }

            //弓术
            ActivityInfo bowArtActivityInfo = BowArtMgr.getActivityInfo();
            if(ActivityMgr.activityInTime(bowArtActivityInfo)){
                int type = BowArtMgr.CONDITION_TYPE_SERVER_UNION;
                List<ActivityConditionInfo> list = NormalActivityMgr.getActivityConditionInfoList(bowArtActivityInfo.getActivityId());
                if(list != null) {
                    for (ActivityConditionInfo activityConditionInfo : list) {
                        if (activityConditionInfo.getType() == BowArtMgr.CONDITION_TYPE_CROSS_UNION) {
                            type = BowArtMgr.CONDITION_TYPE_CROSS_UNION;
                            break;
                        }
                    }
                    GeneralActivityRankMgr.changeUnionActivityValue(bowArtActivityInfo.getActivityId(), type, unionUid, userId, null, UnionRiseRankArgs.NOTIFY_TYPE_POSITION_CHANGE);
                }
            }

            //据点
            if (!StrongholdActivityMgr.isGameFinish()) {
                ActivityInfo strongholdActivityInfo = StrongholdActivityMgr.getOpenActivityInfo();
                if (strongholdActivityInfo != null) {
                    StrongholdActivityRankMgr.changeUnionActivityValue(strongholdActivityInfo.getActivityId(), StrongholdActivityMgr.CONDITION_TYPE_WILD_UNION, unionUid, userId, null, UnionRiseRankArgs.NOTIFY_TYPE_POSITION_CHANGE);
                    StrongholdActivityRankMgr.changeUnionActivityValueNotUpload(strongholdActivityInfo.getActivityId(), StrongholdActivityMgr.CONDITION_TYPE_ELIMINATE_UNION, unionUid, userId, null, UnionRiseRankArgs.NOTIFY_TYPE_POSITION_CHANGE);
                }
            }

            // 大富翁
            DFWConfig dfwConfig = DaFuWengMgr.getDfwConfig();
            if (dfwConfig != null && ActivityMgr.activityInTime(dfwConfig.getActivityInfo())) {
                for (int type : NormalActivityMgr.getActivityConditionUnionRankType(dfwConfig.getActivityInfo().getActivityId())) {
                    GeneralActivityRankMgr.changeUnionActivityValue(dfwConfig.getActivityInfo().getActivityId(), type, unionUid, userId, null, UnionRiseRankArgs.NOTIFY_TYPE_POSITION_CHANGE);
                }
            }
            // 鬼市
            ActivityInfo ghostInfo = GhostMgr.getActivityInfo();
            if (ActivityMgr.activityInTime(ghostInfo)) {
                for (int type : NormalActivityMgr.getActivityConditionUnionRankType(ghostInfo.getActivityId())) {
                    GeneralActivityRankMgr.changeUnionActivityValue(ghostInfo.getActivityId(), type, unionUid, userId, null, UnionRiseRankArgs.NOTIFY_TYPE_POSITION_CHANGE);
                }
            }
            // 统兵演武
            TongBingMgr.unionChange(unionUid);
            TonBingMgr.unionChange(unionUid);
            ChannelTonBingMgr.unionChange(unionUid);
            // 赛龙舟
            ActivityInfo dragonBoatRaceInfo = DragonBoatRaceMgr.getActivityInfo();
            if (ActivityMgr.activityInTime(dragonBoatRaceInfo)) {
                for (int type : NormalActivityMgr.getActivityConditionUnionRankType(dragonBoatRaceInfo.getActivityId())) {
                    GeneralActivityRankMgr.changeUnionActivityValue(dragonBoatRaceInfo.getActivityId(), type, unionUid, userId, null, UnionRiseRankArgs.NOTIFY_TYPE_POSITION_CHANGE);
                }
            }
            //秦始皇陵
            ActivityInfo tombInfo = TombMgr.getActivityInfo();
            if (ActivityMgr.activityInTime(ghostInfo)) {
                for (int type : NormalActivityMgr.getActivityConditionUnionRankType(tombInfo.getActivityId())) {
                    GeneralActivityRankMgr.changeUnionActivityValue(tombInfo.getActivityId(), type, unionUid, userId, null, UnionRiseRankArgs.NOTIFY_TYPE_POSITION_CHANGE);
                }
            }
        } catch (Exception e) {
            logger.error("notifyUnionActivityMemberPositionChange", e);
        }
    }

    private static void notifyUnionActivityMasterChange(long userId, String unionUid) {
        notifyCommonActivityMasterChange(unionUid);
        List<ActivityInfo> activityInfoList = NormalActivityMgr.getUnionRiseRankActivityList();
        for (ActivityInfo activityInfo : activityInfoList) {
            UnionActivityMgr.changeUnionActivityValue(activityInfo.getActivityId(), unionUid, 0, null, UnionRiseRankArgs.NOTIFY_TYPE_NORMAL);
        }
        if (!StrongholdActivityMgr.isGameFinish()) {
            ActivityInfo strongholdActivityInfo = StrongholdActivityMgr.getOpenActivityInfo();
            if (strongholdActivityInfo != null) {
                StrongholdActivityRankMgr.changeUnionActivityValue(strongholdActivityInfo.getActivityId(), StrongholdActivityMgr.CONDITION_TYPE_WILD_UNION, unionUid, userId, null, UnionRiseRankArgs.NOTIFY_TYPE_NORMAL);
                StrongholdActivityRankMgr.changeUnionActivityValueNotUpload(strongholdActivityInfo.getActivityId(), StrongholdActivityMgr.CONDITION_TYPE_ELIMINATE_UNION, unionUid, userId, null, UnionRiseRankArgs.NOTIFY_TYPE_NORMAL);
            }
        }

        //弓术
        ActivityInfo bowArtActivityInfo = BowArtMgr.getActivityInfo();
        if(ActivityMgr.activityInTime(bowArtActivityInfo)){
            int type = BowArtMgr.CONDITION_TYPE_SERVER_UNION;
            List<ActivityConditionInfo> list = NormalActivityMgr.getActivityConditionInfoList(bowArtActivityInfo.getActivityId());
            if(list != null) {
                for (ActivityConditionInfo activityConditionInfo : list) {
                    if (activityConditionInfo.getType() == BowArtMgr.CONDITION_TYPE_CROSS_UNION) {
                        type = BowArtMgr.CONDITION_TYPE_CROSS_UNION;
                        break;
                    }
                }
                GeneralActivityRankMgr.changeUnionActivityValue(bowArtActivityInfo.getActivityId(), type, unionUid, userId, null, UnionRiseRankArgs.NOTIFY_TYPE_POSITION_CHANGE);
            }
        }

        // 大富翁
        DFWConfig dfwConfig = DaFuWengMgr.getDfwConfig();
        if (dfwConfig != null && ActivityMgr.activityInTime(dfwConfig.getActivityInfo())) {
            for (int type : NormalActivityMgr.getActivityConditionUnionRankType(dfwConfig.getActivityInfo().getActivityId())) {
                GeneralActivityRankMgr.changeUnionActivityValue(dfwConfig.getActivityInfo().getActivityId(), type, unionUid, userId, null, UnionRiseRankArgs.NOTIFY_TYPE_POSITION_CHANGE);
            }
        }
        // 鬼市
        ActivityInfo ghostInfo = GhostMgr.getActivityInfo();
        if (ActivityMgr.activityInTime(ghostInfo)) {
            for (int type : NormalActivityMgr.getActivityConditionUnionRankType(ghostInfo.getActivityId())) {
                GeneralActivityRankMgr.changeUnionActivityValue(ghostInfo.getActivityId(), type, unionUid, userId, null, UnionRiseRankArgs.NOTIFY_TYPE_POSITION_CHANGE);
            }
        }
        // 统兵演武
        TongBingMgr.unionChange(unionUid);
        TonBingMgr.unionChange(unionUid);
        ChannelTonBingMgr.unionChange(unionUid);
        // 赛龙舟
        ActivityInfo dragonBoatRaceInfo = DragonBoatRaceMgr.getActivityInfo();
        if (ActivityMgr.activityInTime(dragonBoatRaceInfo)) {
            for (int type : NormalActivityMgr.getActivityConditionUnionRankType(dragonBoatRaceInfo.getActivityId())) {
                GeneralActivityRankMgr.changeUnionActivityValue(dragonBoatRaceInfo.getActivityId(), type, unionUid, userId, null, UnionRiseRankArgs.NOTIFY_TYPE_POSITION_CHANGE);
            }
        }
        //秦始皇陵
        ActivityInfo tombInfo = TombMgr.getActivityInfo();
        if (ActivityMgr.activityInTime(ghostInfo)) {
            for (int type : NormalActivityMgr.getActivityConditionUnionRankType(tombInfo.getActivityId())) {
                GeneralActivityRankMgr.changeUnionActivityValue(tombInfo.getActivityId(), type, unionUid, userId, null, UnionRiseRankArgs.NOTIFY_TYPE_POSITION_CHANGE);
            }
        }
    }

    private static void notifyCommonActivityMasterChange(String unionUid) {
        List<ActivityInfo> activityInfoList = CommonActivityMgr.getInTimeCommonActivityInfoList(eActivityType.CommonActivity.getValue());
        for (ActivityInfo activityInfo : activityInfoList) {
            CommonActivityRankMgr.changeUnionActivityValue(activityInfo.getActivityId(), unionUid, 0, null, UnionRiseRankArgs.NOTIFY_TYPE_NORMAL);
        }
    }

    public static UnionConstructResult constructUnion(GamePlayer player, int constructType) {
        UnionConstructResult result = new UnionConstructResult();
        String unionUid = player.getUserInfo().getUnionUid();
        UnionInfo unionInfo = getUnionInfo(unionUid);
        if (null == unionInfo) {
            result.setRet(GameErrorCode.E_UNION_NO_JOIN_UNION);
            return result;
        }
        resetUnionDailyData(unionInfo);
        UnionMember unionMember = getUnionMember(unionUid, player.getUserId());
        if (null == unionMember) {
            result.setRet(GameErrorCode.E_UNION_NO_JOIN_UNION);
            return result;
        }
        resetMemberDailyData(unionMember);
        UnionConstructConfig unionConstructConfig = UnionConfigMgr.getUnionConstructConfig(constructType);
        if (null == unionConstructConfig) {
            result.setRet(GameErrorCode.E_UNION_CONSTRUCT_TYPE_ERROR);
            return result;
        }
        int constructTimes = unionMember.getConstructTimes(constructType);
        if (constructTimes >= unionConstructConfig.getMaxTimes()) {
            result.setRet(GameErrorCode.E_UNION_CONSTRUCT_TIME_OVER);
            return result;
        }
        long nowTime = System.currentTimeMillis() / 1000;
        long lastConstructTime = unionMember.getLastConstructTime(constructType);
        if (nowTime - lastConstructTime < unionConstructConfig.getCoolTime()) {
            result.setRet(GameErrorCode.E_UNION_CONSTRUCT_COOL_TIME);
            return result;
        }
        synchronized (unionInfo) {
            if (!unionInfo.hasConstructUserId(player.getUserId()) && unionInfo.getConstructUserCount() >= (UnionConfigMgr.getMaxMemberCount(unionInfo.getExperience()) +
                    GameConfig.UNION_CONSTRUCTION_MAX_ADD_MEMBER_COUNT)) {
                result.setRet(GameErrorCode.E_UNION_CONSTRUCT_MEMBER_OVER);
                return result;
            }
            //消耗
            boolean needConsume = true;
            if (2 == constructType) {
                if (player.getModule(CardModule.class).isUnionConstructMidFree()) {
                    needConsume = false;
                }
            } else if (3 == constructType) {
                if (player.getModule(CardModule.class).isUnionConstructSupFree()) {
                    needConsume = false;
                }
            }
            if (needConsume) {
                if (!player.getModule(CurrencyModule.class).removeCurrency(unionConstructConfig.getConsume(), eLogMoneyType.Union, eLogMoneyType.UnionConstruct)) {
                    result.setRet(GameErrorCode.E_BAG_ITEM_NO_ENOUGH);
                    return result;
                }
                result.setConsume(unionConstructConfig.getConsume());
            }
            //增加建设次数
            unionMember.addConstructTimes(constructType);
            unionInfo.addConstructUserId(player.getUserId());
            unionInfo.setConstructActive(unionInfo.getConstructActive() + unionConstructConfig.getAddProgress());
        }
        //奖励
        Property reward = new Property();
        reward.addProperty(GameConfig.GAME_ITEM_UNION_CONTRIBUTION, BigInteger.valueOf(unionConstructConfig.getAddContribution()));
        reward.addProperty(GameConfig.GAME_ITEM_UNION_EXP, BigInteger.valueOf(unionConstructConfig.getAddUnionExp()));
        reward.addProperty(GameConfig.GAME_ITEM_UNION_WEALTH, BigInteger.valueOf(unionConstructConfig.getAddUnionWealth()));
        //奖励入口袋
        player.getModule(CurrencyModule.class).addCurrency(reward, eLogMoneyType.Union, eLogMoneyType.UnionConstruct);
        AttributeModule attributeModule = player.getModule(AttributeModule.class);
        attributeModule.addAttribute(ePlayerAttrType.UnionTotalConstructTimes, 1);
        //任务、成就
        player.notifyListener(eGamePlayerEventType.UnionConstructTimes.getValue(), 1);
        player.notifyListener(eGamePlayerEventType.UnionUnionConstructTimes.getValue(), new UnionActivityTaskArgs(UnionActivityTaskArgs.TYPE_ADD_VALUE, 1, player.getUserInfo().getUnionUid()));
        player.notifyListener(eGamePlayerEventType.UnionTotalConstructTimes.getValue(), attributeModule.getAttribute(ePlayerAttrType.UnionTotalConstructTimes));
        //增加联盟日志
        UnionNoticeMgr.addNotice(player, unionUid, eUnionNoticeType.ConstructUnion.getValue(), String.valueOf(constructType));
        //给在线成员推送联盟信息
        UnionMgr.notifyAllMemberUnionInfo(unionUid, player.getUserId());
        //变更商会信息
        UnionActivityMgr.changeUnionInfo(unionInfo);
        result.setRet(0);
        result.setReward(reward);
        return result;
    }

    public static int randomJoin(GamePlayer player) {
        synchronized (lockObj) {
            List<UnionInfo> tempUnionList = new ArrayList<>();
            int maxCount = 0;
            for (UnionInfo unionInfo : unionInfoMap.values()) {
                if (!unionInfo.isDelete() && unionInfo.isAllowRandomJoin() && player.getTitleId() >= unionInfo.getApplyTitleLimit()) {
                    if(!SeacraftSouthSeaMgr.canInAndOutUnion(unionInfo.getUnionUid())){
                        continue;
                    }
                    int memberCount = getUnionMemberCount(unionInfo.getUnionUid());
                    if (memberCount < UnionConfigMgr.getMaxMemberCount(unionInfo.getExperience()) && !isDayJoinNumLimit(unionInfo)) {
                        if (memberCount > maxCount) {
                            maxCount = memberCount;
                            tempUnionList.clear();
                            tempUnionList.add(unionInfo);
                        } else if (memberCount == maxCount) {
                            tempUnionList.add(unionInfo);
                        }
                    }
                }
            }

            if (tempUnionList.size() > 0) {
                int size = random.next(0, tempUnionList.size());
                UnionInfo unionInfo = tempUnionList.get(size);
                addUnionMember(null, unionInfo.getUnionUid(), player.getUserId());
                DouLuoDaLuMgr.unionChange(player);
                return 0;
            } else {
                return GameErrorCode.E_UNION_NO_RANDOM_JOIN;
            }
        }
    }

    /**
     * 是否达到每日加入限制
     */
    private static boolean isDayJoinNumLimit(UnionInfo unionInfo) {
        //是否已开启限制
        ServerInfo serverInfo = ServerListMgr.getServerInfo(GameServer.getInstance().getServerId());
        int days = DateHelper.calc2DateTDOADays(new Date(serverInfo.getOpenTime() * 1000), new Date());
        if(days < GameConfig.UNION_PER_DAY_JOIN_NUM_LIMIT_OPEN_TIME){
            return false;
        }
        if(unionInfo.getDayJoinNum() >= GameConfig.UNION_PER_DAY_JOIN_NUM_LIMIT){
            return true;
        }
        return false;
    }


    public static void playerCheckUnionValid(GamePlayer player) {
        String unionUid = player.getUserInfo().getUnionUid();
        if (!StringUtils.isNullOrEmpty(unionUid)) {
            UnionInfo unionInfo = getUnionInfo(unionUid);
            UnionMember unionMember = getUnionMember(unionUid, player.getUserId());
            int chamberPatronsId = 0;
            if (null == unionInfo || unionInfo.isDelete() || null == unionMember) {
                if (null != unionMember) {
                    chamberPatronsId = unionMember.getChamberPatronsId();
                    unionMember.setUnionUid("");
                    //清除议事厅数据
                    unionMember.setChamberPatronsId(0);
                    unionMember.setChamberPatron(null);
                    removeMemberFromMap(unionUid, player.getUserId());
                    addMemberToDeleteMap(unionMember);
                }
                if (null != unionInfo) {
                    synchronized (unionInfo) {
                        if (getUnionMemberCount(unionUid) > 0 && chamberPatronsId > 0) {//商会有人
                            notifyAllMemberChamberChange(unionUid, player.getUserId(), true, null);
                        } else {//商会没人了
                            unionInfo.setDelete(true);
                        }
                    }
                }
                player.getUserInfo().setUnionUid("");
            }
        }
    }

    private static int removeFormUnion(GamePlayer player, UnionInfo unionInfo, long removeUserId, int removeType) {
        // 扣除贡献值
        UnionMember removeMember = getUnionMember(unionInfo.getUnionUid(), removeUserId);
        long oldContribution;
        long nowContribution;
        if (null != removeMember) {
            removeMember.setUnionUid("");
            removeMember.setQuitTime(System.currentTimeMillis() / 1000);
            if (eUnionSyncType.BeKick.getValue() == removeType || eUnionSyncType.DeleteUnion.getValue() == removeType) {
                if (GameConfig.UNION_NEXT_JOIN_NEED_TIME >= 10 * DateHelper.MINUTE_SECONDS) {
                    removeMember.setQuitTime(System.currentTimeMillis() / 1000 - GameConfig.UNION_NEXT_JOIN_NEED_TIME + 10 * DateHelper.MINUTE_SECONDS);
                }
            }
            oldContribution = removeMember.getContribution();
            removeMember.setContribution(UnionConfigMgr.getLoseContribution(removeMember.getContribution()));
            //清除议事厅数据
            removeMember.setChamberPatronsId(0);
            removeMember.setChamberPatron(null);
            nowContribution = removeMember.getContribution();
            int son = 0;
            if (eUnionSyncType.QuitUnion.getValue() == removeType) {
                son = eLogMoneyType.UnionQuit.getValue();
            } else if (eUnionSyncType.BeKick.getValue() == removeType) {
                son = eLogMoneyType.UnionBeKick.getValue();
            } else if (eUnionSyncType.DeleteUnion.getValue() == removeType) {
                son = eLogMoneyType.UnionDelete.getValue();
            }
            //清理副业数据
            UnionParergonMgr.quitUnion(unionInfo.getUnionUid(), removeUserId);

            AutoLogMgr.add(new LogUnionContribution(removeUserId, unionInfo.getUnionUid(), false, oldContribution - nowContribution,
                    oldContribution, nowContribution, son));

            addMemberToDeleteMap(removeMember);
        } else {
            return GameErrorCode.E_UNION_MEMBER_NO_FOUND;
        }

        // 通知被踢出家族
        GamePlayer removePlayer = GamePlayerMgr.getOnlinePlayer(removeUserId);
        UserInfo removeUserInfo = null;
        if (null != removePlayer) {
            removeUserInfo = removePlayer.getUserInfo();
            removeUserInfo.setUnionUid("");
            removePlayer.sendPacket(Protocol.U_UNION_DETAIL, getUnionDetailMsg(unionInfo.getUnionUid(), removeType));
            removePlayer.sendPacket(Protocol.U_UNION_MEMBER_SYNC, UnionPb.parseUnionMemberTempMsg(removeMember));
            removePlayer.notifyListener(eGamePlayerEventType.JoinUnion.getValue(), removeUserInfo);
            removePlayer.notifyListener(eGamePlayerEventType.JoinUnionActivityCondition.getValue(), removeUserInfo);
            removePlayer.getModule(ChatModule.class).clearUnionForbiddenMessage();
        } else {
            removeUserInfo = UserMgr.getUserInfo(removeUserId);
            if (null != removeUserInfo) {
                removeUserInfo.setUnionUid("");
            }
            UserBussiness.updateUnionUid(removeUserId, "");
        }
        //通知议事厅
        notifyAllMemberChamberChange(unionInfo.getUnionUid(), removeUserId, true, null);
        removeMemberFromMap(unionInfo.getUnionUid(), removeUserId);
        unionInfo.setMemberCount(getUnionMemberCount(unionInfo.getUnionUid()));
        calcUnionEarnSpeed(unionInfo);
        RankMgr.changeUnionRank(unionInfo);
        //商会冲榜
        removeMemberActivityConditionData(removeUserId, unionInfo.getUnionUid());
        if (eUnionSyncType.BeKick.getValue() == removeType) {
            String mailTitle = MultipleLanguageMgr.getContent(MailManager.UNION_BE_KICK_TITLE, UserMgr.getLanguage(removeUserId));
            String mailContent = StringUtils.format(MultipleLanguageMgr.getContent(MailManager.UNION_BE_KICK_CONTENT, UserMgr.getLanguage(removeUserId)),
                    player.getUserInfo().getNickName(), oldContribution - nowContribution, nowContribution);
            MailManager.sendMail(removeUserId, eMailType.SYSTEM.getValue(), "", mailContent, mailTitle);
        } else if (eUnionSyncType.DeleteUnion.getValue() == removeType) {
            String mailTitle = MultipleLanguageMgr.getContent(MailManager.UNION_DELETE_TITLE, UserMgr.getLanguage(removeUserId));
            String mailContent = StringUtils.format(MultipleLanguageMgr.getContent(MailManager.UNION_DELETE_CONTENT, UserMgr.getLanguage(removeUserId)),
                    oldContribution - nowContribution, nowContribution);
            MailManager.sendMail(removeUserId, eMailType.SYSTEM.getValue(), "", mailContent, mailTitle);
        }

        MonopolyMarketMgr.leaveUnion(unionInfo.getUnionUid(), removeUserId);
        //DataAnalyticsMgr.trackUnionLeaveGuild(removeUserId,unionInfo,removeMember.getPosition());
        UserMgr.addNeedUpdateToCrossMap(removeUserId,removeUserInfo);
        return 0;
    }

    public static void memberJoinUnionActivityChange(long userId, String unionUid) {
        memberJoinUnionCommonActivityChange(userId, unionUid);
        memberJoinUnionOreWarActivityChange(userId, unionUid);
        memberJoinUnionCrossTradeWarChange(userId, unionUid);
        memberJoinUnionCrossStrongholdChange(userId, unionUid);
        memberJoinUnionDfwChange(userId, unionUid);
        memberJoinUnionBowArtChange(userId, unionUid);
        memberJoinUnionGhostChange(userId, unionUid);
        TongBingMgr.unionChange(unionUid);
        TonBingMgr.unionChange(unionUid);
        ChannelTonBingMgr.unionChange(unionUid);
        memberJoinUnionDragonBoatRaceChange(userId, unionUid);
        memberJoinUnionTwinsChange(userId, unionUid);
        memberJoinUnionRelationActivityChange(userId, unionUid);
        memberJoinUnionSeacraftPirateRiotChange(userId, unionUid);
        GamePlayer player = GamePlayerMgr.getOnlinePlayer(userId);
        if (null != player) {
            player.notifyListener(eGamePlayerEventType.UnionExpRiseRank.getValue(), new UnionRiseRankArgs(UnionRiseRankArgs.NOTIFY_TYPE_JOIN, BigInteger.ZERO, unionUid));
            player.notifyListener(eGamePlayerEventType.UnionTradeWarScoreRiseRank.getValue(), new UnionRiseRankArgs(UnionRiseRankArgs.NOTIFY_TYPE_JOIN, BigInteger.ZERO, unionUid));
            player.notifyListener(eGamePlayerEventType.UnionIntimacyRiseRank.getValue(), new UnionRiseRankArgs(UnionRiseRankArgs.NOTIFY_TYPE_JOIN, BigInteger.ZERO, unionUid));
            player.notifyListener(eGamePlayerEventType.UnionAbilityRiseRank.getValue(), new UnionRiseRankArgs(UnionRiseRankArgs.NOTIFY_TYPE_JOIN, BigInteger.ZERO, unionUid));
            player.notifyListener(eGamePlayerEventType.UnionEarnSpeedRiseRank.getValue(), new UnionRiseRankArgs(UnionRiseRankArgs.NOTIFY_TYPE_JOIN, BigInteger.ZERO, unionUid));
        } else {
            List<ActivityInfo> activityInfoList = NormalActivityMgr.getUnionRiseRankActivityList();
            for (ActivityInfo activityInfo : activityInfoList) {
                List<ActivityConditionInfo> activityConditionInfoList = NormalActivityMgr.getActivityConditionInfoList(activityInfo.getActivityId());
                UserActivityConditionData userActivityConditionData = null;
                if (null != activityConditionInfoList && activityConditionInfoList.size() > 0) {
                    userActivityConditionData = UserActivityBussiness.getUserActivityConditionData(activityInfo.getActivityId(), userId);
                    if (null == userActivityConditionData) {
                        userActivityConditionData = NormalActivityMgr.initUserActivityConditionData(userId, UserMgr.getNickName(userId), BigInteger.ZERO,
                                activityInfo.getActivityId(), activityConditionInfoList.get(0).getConditionId(), activityConditionInfoList.get(0).getType());
                        UserActivityBussiness.addUserActivityConditionData(userActivityConditionData);
                    }
                }
                if (null != userActivityConditionData) {
                    UnionActivityMgr.changeUnionActivityValue(activityInfo.getActivityId(), unionUid, userActivityConditionData.getUserId(), userActivityConditionData, UnionRiseRankArgs.NOTIFY_TYPE_JOIN);
                }
            }
        }
    }

    private static void memberJoinUnionTwinsChange(long userId, String unionUid) {
        try {
            ActivityInfo activityInfo = TwinsMgr.getActivity();
            if (ActivityMgr.activityInTime(activityInfo)) {
                int activityId = activityInfo.getActivityId();
                List<Integer> typeList = NormalActivityMgr.getActivityConditionUnionRankType(activityId);
                for (Integer type : typeList) {
                    List<UserActivityConditionData> dataList = UserActivityBussiness.getUserActivityConditionDataListByUserIdAndType(activityId, userId, type);
                    if (dataList != null && dataList.size() > 0) {
                        UserActivityConditionData userActivityConditionData = dataList.get(0);
                        GeneralActivityRankMgr.changeUnionActivityValue(activityId, type, unionUid, userId, userActivityConditionData, UnionRiseRankArgs.NOTIFY_TYPE_JOIN);
                    }
                }
            }
        } catch (Exception e) {

        }
    }

    private static void memberJoinUnionGhostChange(long userId, String unionUid) {
        try {
            ActivityInfo activityInfo = GhostMgr.getActivityInfo();
            if (ActivityMgr.activityInTime(activityInfo)) {
                int activityId = activityInfo.getActivityId();
                List<Integer> typeList = NormalActivityMgr.getActivityConditionUnionRankType(activityId);
                for (Integer type : typeList) {
                    List<UserActivityConditionData> dataList = UserActivityBussiness.getUserActivityConditionDataListByUserIdAndType(activityId, userId, type);
                    if (dataList != null && dataList.size() > 0) {
                        UserActivityConditionData userActivityConditionData = dataList.get(0);
                        GeneralActivityRankMgr.changeUnionActivityValue(activityId, type, unionUid, userId, userActivityConditionData, UnionRiseRankArgs.NOTIFY_TYPE_JOIN);
                    }
                }
            }
        } catch (Exception e) {

        }
    }

    private static void memberJoinUnionBowArtChange(long userId, String unionUid){
        try{
            ActivityInfo activityInfo = BowArtMgr.getActivityInfo();
            if(ActivityMgr.activityInTime(activityInfo)){
                int activityId = activityInfo.getActivityId();
                List<Integer> typeList = NormalActivityMgr.getActivityConditionUnionRankType(activityId);
                for (Integer type : typeList) {
                    List<UserActivityConditionData> dataList = UserActivityBussiness.getUserActivityConditionDataListByUserIdAndType(activityId, userId, type);
                    if (dataList != null && dataList.size() > 0) {
                        UserActivityConditionData userActivityConditionData = dataList.get(0);
                        GeneralActivityRankMgr.changeUnionActivityValue(activityId, type, unionUid, userId, userActivityConditionData, UnionRiseRankArgs.NOTIFY_TYPE_JOIN);
                    }
                }
            }
        }catch (Exception e) {

        }
    }

    private static void memberJoinUnionDragonBoatRaceChange(long userId, String unionUid){
        try{
            if(ActivityMgr.activityInTime(DragonBoatRaceMgr.getActivityInfo())){
                int activityId = DragonBoatRaceMgr.getActivityInfo().getActivityId();
                List<Integer> typeList = NormalActivityMgr.getActivityConditionUnionRankType(activityId);
                for (Integer type : typeList) {
                    List<UserActivityConditionData> dataList = UserActivityBussiness.getUserActivityConditionDataListByUserIdAndType(activityId, userId, type);
                    if (dataList != null && dataList.size() > 0) {
                        UserActivityConditionData userActivityConditionData = dataList.get(0);
                        GeneralActivityRankMgr.changeUnionActivityValue(activityId, type, unionUid, userId, userActivityConditionData, UnionRiseRankArgs.NOTIFY_TYPE_JOIN);
                    }
                }
            }
        }catch (Exception e) {

        }
    }

    private static void memberJoinUnionDfwChange(long userId, String unionUid) {
        try {
            DaFuWengMgr.notifyUnionData(GamePlayerMgr.getOnlinePlayer(userId));
            DaFuWengMgr.unionMemberChange(new ArrayList<>(getUnionMemberMap(unionUid).keySet()));
            DFWConfig dfwConfig = DaFuWengMgr.getDfwConfig();
            if (dfwConfig == null) {
                return;
            }
            if (ActivityMgr.activityInTime(dfwConfig.getActivityInfo())) {
                int activityId = dfwConfig.getActivityInfo().getActivityId();
                List<Integer> typeList = NormalActivityMgr.getActivityConditionUnionRankType(activityId);
                for (Integer type : typeList) {
                    List<UserActivityConditionData> dataList = UserActivityBussiness.getUserActivityConditionDataListByUserIdAndType(activityId, userId, type);
                    if (dataList != null && dataList.size() > 0) {
                        UserActivityConditionData userActivityConditionData = dataList.get(0);
                        GeneralActivityRankMgr.changeUnionActivityValue(dfwConfig.getActivityInfo().getActivityId(), type, unionUid, userId, userActivityConditionData, UnionRiseRankArgs.NOTIFY_TYPE_JOIN);
                    }
                }
            }

        } catch (Exception e) {

        }
    }

    private static void memberJoinUnionSeacraftPirateRiotChange(long userId, String unionUid) {
        try {
            SeacraftPirateRiotConfig config = SeacraftPirateRiotMgr.getPirateRiotConfig();
            if (SeacraftPirateRiotMgr.inUnionRankChangeTime(config)) {
                int activityId = config.getActivityInfo().getActivityId();
                int type = eGamePlayerEventType.SeacraftPirateRiotUnionScoreRank.getValue();
                List<UserActivityConditionData> dataList = UserActivityBussiness.getUserActivityConditionDataListByUserIdAndType(activityId, userId, type);
                if (dataList != null && dataList.size() > 0) {
                    UserActivityConditionData userActivityConditionData = dataList.get(0);
                    GeneralActivityRankMgr.changeUnionActivityValue(activityId, type, unionUid, userId, userActivityConditionData, UnionRiseRankArgs.NOTIFY_TYPE_JOIN);
                }
            }
        } catch (Exception e) {

        }
    }

    private static void removeMemberSeacraftPirateRiotChange(long userId, String unionUid) {
        SeacraftPirateRiotConfig config = SeacraftPirateRiotMgr.getPirateRiotConfig();
        if (SeacraftPirateRiotMgr.inUnionRankChangeTime(config)) {
            ActivityInfo activityInfo = config.getActivityInfo();
            GeneralActivityRankMgr.changeUnionActivityValue(activityInfo.getActivityId(), eGamePlayerEventType.SeacraftPirateRiotUnionScoreRank.getValue(), unionUid, userId, null, UnionRiseRankArgs.NOTIFY_TYPE_REMOVE);
        }
    }

    private static void memberJoinUnionCrossStrongholdChange(long userId, String unionUid) {
        ActivityInfo activityInfo = StrongholdActivityMgr.getOpenActivityInfo();
        if (activityInfo != null && !StrongholdActivityMgr.isGameFinish()) {
            GamePlayer player = GamePlayerMgr.getOnlinePlayer(userId);
            if (player != null) {
                player.getModule(StrongholdModule.class).syncUserData();
            }
            StrongholdActivityMgr.conditionNotify(userId, eGamePlayerEventType.StrongholdWildScoreRank.getValue(),
                    new OreWarActivityUnionRiseRankArgs(UnionRiseRankArgs.NOTIFY_TYPE_JOIN, BigInteger.ZERO, unionUid, activityInfo.getActivityId()));
            StrongholdActivityMgr.conditionNotify(userId, eGamePlayerEventType.StrongholdEliminateRank.getValue(),
                    new OreWarActivityUnionRiseRankArgs(UnionRiseRankArgs.NOTIFY_TYPE_JOIN, BigInteger.ZERO, unionUid, activityInfo.getActivityId()));
        }
    }


    /**
     * 成员加入商会，万能活动商会处理
     */
    private static void memberJoinUnionCommonActivityChange(long userId, String unionUid) {
        GamePlayer player = GamePlayerMgr.getOnlinePlayer(userId);
        List<ActivityInfo> activityInfoList = CommonActivityMgr.getInTimeCommonActivityInfoList(eActivityType.CommonActivity.getValue());
        if (null != player) {
            for (ActivityInfo activityInfo : activityInfoList) {
                player.notifyListener(eGamePlayerEventType.CommonActivityScoreRiseRank.getValue(),
                        new CommonActivityUnionRiseRankArgs(UnionRiseRankArgs.NOTIFY_TYPE_JOIN, BigInteger.ZERO, unionUid, activityInfo.getChildType()));
            }
        } else {
            for (ActivityInfo activityInfo : activityInfoList) {
                List<ActivityConditionInfo> activityConditionInfoList = CommonActivityMgr.getCommonActivityConditionInfoList(activityInfo.getActivityId(),
                        ActivityHelper.COMMON_ACTIVITY_CONDITION_TYPE_UNION);
                UserActivityConditionData userActivityConditionData = null;
                if (null != activityConditionInfoList && activityConditionInfoList.size() > 0) {
                    List<UserActivityConditionData> conditionDataList = UserCommonActivityBussiness.getUserActivityConditionDataList(activityInfo.getActivityId(), userId,
                            ActivityHelper.COMMON_ACTIVITY_CONDITION_TYPE_UNION);
                    for (UserActivityConditionData conditionData : conditionDataList) {
                        ActivityConditionInfo conditionInfo = CommonActivityMgr.getCommonActivityConditionInfo(activityInfo.getActivityId(), conditionData.getConditionId());
                        if (conditionInfo.getType() == ActivityHelper.COMMON_ACTIVITY_CONDITION_TYPE_UNION) {
                            userActivityConditionData = conditionData;
                            break;
                        }
                    }
                    if (null == userActivityConditionData) {
                        userActivityConditionData = NormalActivityMgr.initUserActivityConditionData(userId, UserMgr.getNickName(userId), BigInteger.ZERO,
                                activityInfo.getActivityId(), activityConditionInfoList.get(0).getConditionId(), activityConditionInfoList.get(0).getType());
                        UserCommonActivityBussiness.addUserCommonActivityConditionData(userActivityConditionData);
                    }
                }
                if (null != userActivityConditionData) {
                    CommonActivityRankMgr.changeUnionActivityValue(activityInfo.getActivityId(), unionUid, userActivityConditionData.getUserId(), userActivityConditionData, UnionRiseRankArgs.NOTIFY_TYPE_JOIN);
                }
            }
        }
    }

    /**
     * 成员加入商会，盐场活动商会处理
     */
    private static void memberJoinUnionOreWarActivityChange(long userId, String unionUid) {
        List<ActivityInfo> activityInfoList = OreWarActivityMgr.getOpenActivityInfoList();
        for (ActivityInfo activityInfo : activityInfoList) {
            if (activityInfo.getChildType() == 1) {
                OreWarActivityMgr.conditionNotify(userId, eGamePlayerEventType.OreWarAcCoinOutPut.getValue(),
                        new OreWarActivityUnionRiseRankArgs(UnionRiseRankArgs.NOTIFY_TYPE_JOIN, BigInteger.ZERO, unionUid, activityInfo.getActivityId()));
            } else if (activityInfo.getChildType() == 2) {
                OreWarActivityMgr.conditionNotify(userId, eGamePlayerEventType.CrossOreWarAcCoinOutPut.getValue(),
                        new OreWarActivityUnionRiseRankArgs(UnionRiseRankArgs.NOTIFY_TYPE_JOIN, BigInteger.ZERO, unionUid, activityInfo.getActivityId()));
            }
        }
    }

    /**
     * 成员加入商会，盐场活动商会处理
     */
    private static void memberJoinUnionRelationActivityChange(long userId, String unionUid) {
        List<ActivityInfo> activityInfoList = RelationActivityMgr.getOpenActivityInfoList();
        for (ActivityInfo activityInfo : activityInfoList) {
            if (activityInfo.getType() == eActivityType.CookingBoyActivity.getValue() && activityInfo.getChildType() == eActivityCookBoyType.Process1.getChildType()) {
                if (ActivityMgr.activityInTime(activityInfo)) {
                    RelationActivityMgr.conditionNotify(activityInfo.getActivityId(),userId, eGamePlayerEventType.CookBoy1IntegralUserCrossRank.getValue(),
                            new RelationActivityUnionRiseRankArgs(UnionRiseRankArgs.NOTIFY_TYPE_JOIN, BigInteger.ZERO, unionUid, activityInfo.getActivityId()));
                }
            } else if (activityInfo.getType() == eActivityType.CookingBoyActivity.getValue() && activityInfo.getChildType() == eActivityCookBoyType.Process2.getChildType()) {
                //其他两个活动没有

            }
        }
    }

    /**
     * 成员加入商会，跨服商战活动商会处理
     */
    private static void memberJoinUnionCrossTradeWarChange(long userId, String unionUid) {
        ActivityInfo activityInfo = TradeWarActivityMgr.getInTimeActivityInfo();
        if (null == activityInfo) {
            return;
        }
        if (!TradeWarActivityMgr.unionCanCrossTradeWar(unionUid)) {//没有资格的商会
            return;
        }
        GamePlayer player = GamePlayerMgr.getOnlinePlayer(userId);
        if (null != player) {
            player.notifyListener(eGamePlayerEventType.CrossTradeWarUnionScoreRiseRank.getValue(),
                    new UnionRiseRankArgs(UnionRiseRankArgs.NOTIFY_TYPE_JOIN, BigInteger.ZERO, unionUid));
        } else {
            List<ActivityConditionInfo> activityConditionInfoList = TradeWarActivityMgr.getActivityConditionInfoList(activityInfo.getActivityId(), TradeWarActivityMgr.CONDITION_TYPE_UNION);
            UserActivityConditionData userActivityConditionData = null;
            if (null != activityConditionInfoList && activityConditionInfoList.size() > 0) {
                List<UserActivityConditionData> conditionDataList = UserTradeWarActivityBussiness.getUserActivityConditionDataList(activityInfo.getActivityId(), userId, TradeWarActivityMgr.CONDITION_TYPE_UNION);
                for (UserActivityConditionData conditionData : conditionDataList) {
                    ActivityConditionInfo conditionInfo = TradeWarActivityMgr.getActivityConditionInfo(activityInfo.getActivityId(), conditionData.getConditionId());
                    if (conditionInfo.getType() == TradeWarActivityMgr.CONDITION_TYPE_UNION) {
                        userActivityConditionData = conditionData;
                        break;
                    }
                }
                if (null == userActivityConditionData) {
                    userActivityConditionData = NormalActivityMgr.initUserActivityConditionData(userId, UserMgr.getNickName(userId), BigInteger.ZERO,
                            activityInfo.getActivityId(), activityConditionInfoList.get(0).getConditionId(), activityConditionInfoList.get(0).getType());
                    UserTradeWarActivityBussiness.addUserActivityConditionData(userActivityConditionData);
                }
            }
            if (null != userActivityConditionData) {
                TradeWarActivityRankMgr.changeUnionActivityValue(activityInfo.getActivityId(), unionUid, userActivityConditionData.getUserId(),
                        userActivityConditionData, UnionRiseRankArgs.NOTIFY_TYPE_JOIN);
            }
        }
    }

    public static void removeMemberActivityConditionData(long userId, String unionUid) {
        removeMemberCommonActivityConditionData(userId, unionUid);
        removeMemberOreWarActivityConditionData(userId, unionUid);
        removeMemberDaFuWengActivityConditionData(userId, unionUid);
        removeMemberBowArtActivityConditionData(userId, unionUid);
        removeMemberGhostActivityConditionData(userId, unionUid);
        TongBingMgr.unionChange(unionUid);
        TonBingMgr.unionChange(unionUid);
        ChannelTonBingMgr.unionChange(unionUid);
        removeMemberDragonBoatRaceActivityConditionData(userId, unionUid);
        removeMemberTwinsActivityConditionData(userId, unionUid);
        removeMemberRelationActivityConditionData(userId, unionUid);
        removeMemberSeacraftPirateRiotChange(userId, unionUid);
        GamePlayer player = GamePlayerMgr.getOnlinePlayer(userId);
        if (null != player) {
            player.notifyListener(eGamePlayerEventType.UnionExpRiseRank.getValue(), new UnionRiseRankArgs(UnionRiseRankArgs.NOTIFY_TYPE_REMOVE, BigInteger.ZERO, unionUid));
            player.notifyListener(eGamePlayerEventType.UnionTradeWarScoreRiseRank.getValue(), new UnionRiseRankArgs(UnionRiseRankArgs.NOTIFY_TYPE_REMOVE, BigInteger.ZERO, unionUid));
            player.notifyListener(eGamePlayerEventType.UnionIntimacyRiseRank.getValue(), new UnionRiseRankArgs(UnionRiseRankArgs.NOTIFY_TYPE_REMOVE, BigInteger.ZERO, unionUid));
            player.notifyListener(eGamePlayerEventType.UnionAbilityRiseRank.getValue(), new UnionRiseRankArgs(UnionRiseRankArgs.NOTIFY_TYPE_REMOVE, BigInteger.ZERO, unionUid));
            player.notifyListener(eGamePlayerEventType.UnionEarnSpeedRiseRank.getValue(), new UnionRiseRankArgs(UnionRiseRankArgs.NOTIFY_TYPE_REMOVE, BigInteger.ZERO, unionUid));

            UnionRechargeUserArgs args = new UnionRechargeUserArgs(UnionRechargeUserArgs.VALUE_IN, 0, unionUid, userId);
            args.setSetValue(BigInteger.valueOf(0));
            player.notifyListener(eGamePlayerEventType.UnionRechargeUser.getValue(), args);
        } else {
            List<ActivityInfo> activityInfoList = NormalActivityMgr.getUnionRiseRankActivityList();
            for (ActivityInfo activityInfo : activityInfoList) {
                UnionActivityMgr.changeUnionActivityValue(activityInfo.getActivityId(), unionUid, userId, null, UnionRiseRankArgs.NOTIFY_TYPE_REMOVE);
            }
        }
    }

    private static void removeMemberTwinsActivityConditionData(long userId, String unionUid){
        List<ActivityInfo> activityInfoList = NormalActivityMgr.getOpenActivityInfoList(eActivityType.Twins.getValue());
        if (activityInfoList != null) {
            for (ActivityInfo activityInfo : activityInfoList) {
                List<Integer> typeList = NormalActivityMgr.getActivityConditionUnionRankType(activityInfo.getActivityId());
                for (Integer type : typeList) {
                    GeneralActivityRankMgr.changeUnionActivityValue(activityInfo.getActivityId(), type, unionUid, userId, null, UnionRiseRankArgs.NOTIFY_TYPE_REMOVE);
                }
            }
        }
    }


    private static void removeMemberDaFuWengActivityConditionData(long userId, String unionUid) {
        List<ActivityInfo> activityInfoList = NormalActivityMgr.getOpenActivityInfoList(eActivityType.DaFuWeng.getValue());
        if (activityInfoList != null) {
            for (ActivityInfo activityInfo : activityInfoList) {
                List<Integer> typeList = NormalActivityMgr.getActivityConditionUnionRankType(activityInfo.getActivityId());
                for (Integer type : typeList) {
                    GeneralActivityRankMgr.changeUnionActivityValue(activityInfo.getActivityId(), type, unionUid, userId, null, UnionRiseRankArgs.NOTIFY_TYPE_REMOVE);
                }
            }
        }
    }

    private static void removeMemberGhostActivityConditionData(long userId, String unionUid) {
        List<ActivityInfo> activityInfoList = NormalActivityMgr.getOpenActivityInfoList(eActivityType.GhostActivity.getValue());
        if (activityInfoList != null) {
            for (ActivityInfo activityInfo : activityInfoList) {
                List<Integer> typeList = NormalActivityMgr.getActivityConditionUnionRankType(activityInfo.getActivityId());
                for (Integer type : typeList) {
                    GeneralActivityRankMgr.changeUnionActivityValue(activityInfo.getActivityId(), type, unionUid, userId, null, UnionRiseRankArgs.NOTIFY_TYPE_REMOVE);
                }
            }
        }
    }

    private static void removeMemberBowArtActivityConditionData(long userId, String unionUid){
        List<ActivityInfo> activityInfoList = NormalActivityMgr.getOpenActivityInfoList(eActivityType.BowArtActivity.getValue());
        if (activityInfoList != null) {
            for (ActivityInfo activityInfo : activityInfoList) {
                List<Integer> typeList = NormalActivityMgr.getActivityConditionUnionRankType(activityInfo.getActivityId());
                for (Integer type : typeList) {
                    GeneralActivityRankMgr.changeUnionActivityValue(activityInfo.getActivityId(), type, unionUid, userId, null, UnionRiseRankArgs.NOTIFY_TYPE_REMOVE);
                }
            }
        }
    }

    private static void removeMemberDragonBoatRaceActivityConditionData(long userId, String unionUid){
        List<ActivityInfo> activityInfoList = NormalActivityMgr.getOpenActivityInfoList(eActivityType.DragonBoatRaceActivity.getValue());
        if (activityInfoList != null) {
            for (ActivityInfo activityInfo : activityInfoList) {
                List<Integer> typeList = NormalActivityMgr.getActivityConditionUnionRankType(activityInfo.getActivityId());
                for (Integer type : typeList) {
                    GeneralActivityRankMgr.changeUnionActivityValue(activityInfo.getActivityId(), type, unionUid, userId, null, UnionRiseRankArgs.NOTIFY_TYPE_REMOVE);
                }
            }
        }
    }

    private static void removeMemberCommonActivityConditionData(long userId, String unionUid) {
        GamePlayer player = GamePlayerMgr.getOnlinePlayer(userId);
        List<ActivityInfo> activityInfoList = CommonActivityMgr.getInTimeCommonActivityInfoList(eActivityType.CommonActivity.getValue());
        if (null != player) {
            for (ActivityInfo activityInfo : activityInfoList) {
                player.notifyListener(eGamePlayerEventType.CommonActivityScoreRiseRank.getValue(),
                        new CommonActivityUnionRiseRankArgs(UnionRiseRankArgs.NOTIFY_TYPE_REMOVE, BigInteger.ZERO, unionUid, activityInfo.getChildType()));
            }
        } else {
            for (ActivityInfo activityInfo : activityInfoList) {
                CommonActivityRankMgr.changeUnionActivityValue(activityInfo.getActivityId(), unionUid, userId, null, UnionRiseRankArgs.NOTIFY_TYPE_REMOVE);
            }
        }
    }

    //移除商会成员盐场活动排行榜移除玩家
    private static void removeMemberOreWarActivityConditionData(long userId, String unionUid) {
        GamePlayer player = GamePlayerMgr.getOnlinePlayer(userId);
        if (null != player) {
            player.notifyListener(eGamePlayerEventType.OreWarAcCoinOutPut.getValue(), new UnionRiseRankArgs(UnionRiseRankArgs.NOTIFY_TYPE_REMOVE, BigInteger.ZERO, unionUid));
            player.notifyListener(eGamePlayerEventType.CrossOreWarAcCoinOutPut.getValue(), new UnionRiseRankArgs(UnionRiseRankArgs.NOTIFY_TYPE_REMOVE, BigInteger.ZERO, unionUid));
        } else {
            List<ActivityInfo> activityInfoList = OreWarActivityMgr.getOpenActivityInfoList();
            for (ActivityInfo activityInfo : activityInfoList) {
                OreWarActivityRankMgr.changeUnionActivityValue(activityInfo.getActivityId(), unionUid, userId, null, UnionRiseRankArgs.NOTIFY_TYPE_REMOVE);
            }
        }
    }

    private static void removeMemberRelationActivityConditionData(long userId, String unionUid) {
        //为什么上面的没用这种方式
        List<ActivityInfo> activityInfoList = RelationActivityMgr.getOpenActivityInfoList();
        for (ActivityInfo activityInfo : activityInfoList) {
            if (activityInfo.getType() == eActivityType.CookingBoyActivity.getValue() && activityInfo.getChildType() == eActivityCookBoyType.Process1.getChildType()) {
                if (ActivityMgr.activityInTime(activityInfo)) {
                    RelationActivityMgr.conditionNotify(activityInfo.getActivityId(),userId, eGamePlayerEventType.CookBoy1IntegralUserCrossRank.getValue(),
                            new RelationActivityUnionRiseRankArgs(UnionRiseRankArgs.NOTIFY_TYPE_REMOVE, BigInteger.ZERO, unionUid, activityInfo.getActivityId()));
                }
            }
        }
    }

    //加入公会
    public static int addUnionMember(GamePlayer player, String unionUid, long joinUserId) {
        GamePlayer joinPlayer;
        UnionInfo unionInfo = getUnionInfo(unionUid);
        if (null == unionInfo) {
            return GameErrorCode.E_UNION_NO_FOUND;
        }
        UserInfo joinUserInfo = UserMgr.getUserInfo(joinUserId);
        joinPlayer = GamePlayerMgr.getOnlinePlayer(joinUserId);
        synchronized (lockObj) {
            int currentCount = getUnionMemberCount(unionUid);
            if (currentCount >= UnionConfigMgr.getMaxMemberCount(unionInfo.getExperience())) {
                return GameErrorCode.E_UNION_MEMBER_FULL;
            }
            if (isDayJoinNumLimit(unionInfo)){
                return GameErrorCode.E_UNION_PER_DAY_JOIN_NUM_LIMIT;
            }
            if (!StringUtils.isNullOrEmpty(joinUserInfo.getUnionUid())) {
                return GameErrorCode.E_UNION_HAS_JOIN_UNION;
            }
            UnionMember unionMember = UnionMgr.getUnionMember("", joinUserId);
            if (null != unionMember) {
                long nowTime = System.currentTimeMillis() / 1000;
                if (nowTime - unionMember.getQuitTime() < GameConfig.UNION_NEXT_JOIN_NEED_TIME) {
                    return GameErrorCode.E_UNION_NEXT_JOIN_TIME_NO_ENOUGH;
                }
            }
            try {
                //玩家加入商会要结算他在盐场没冠名的奖励
                OreWarMgr.sendUnionNamingJoinQuitReward(unionUid, joinUserId);
            } catch (Exception e) {
                logger.error("addUnionMember", e);
            }
            createUnionMember(unionInfo, joinUserInfo, eUnionPosition.Member.getValue());
            unionInfo.setMemberCount(getUnionMemberCount(unionUid));
            unionInfo.setDayJoinNum(1 + unionInfo.getDayJoinNum());
            calcUnionEarnSpeed(unionInfo);
        }
        //联盟日志
        UnionNoticeMgr.addNotice(player, unionUid, eUnionNoticeType.JoinUnion.getValue(), joinUserInfo.getNickName());
        if (null != joinPlayer) {
            joinPlayer.sendPacket(Protocol.U_UNION_DETAIL, getUnionDetailMsg(unionUid, eUnionSyncType.JoinUnion.getValue()));
            //同步议事厅
            joinPlayer.getModule(UnionModule.class).syncChamberPatronsList();
            joinPlayer.getModule(UnionModule.class).syncChamberData();
            //同步商会聊天
            List<WorldMessageProto.WorldMessageTempMsg.Builder> unionMessageList = WorldMessageMgr.getUnionMessageMsgList(unionUid);
            if (null != unionMessageList) {
                WorldMessageProto.WorldMessageListMsg.Builder messageList = WorldMessageProto.WorldMessageListMsg.newBuilder();
                for (WorldMessageProto.WorldMessageTempMsg.Builder message : unionMessageList) {
                    messageList.addDataList(message);
                }
                joinPlayer.sendPacket(Protocol.U_WORLD_MESSAGE_LIST_SYNC, messageList);
            }
            //同步商会副业
            joinPlayer.getModule(UnionParergonModule.class).loginSendMsg();

            UnionRechargeUserArgs args = new UnionRechargeUserArgs(UnionRechargeUserArgs.VALUE_IN, 0, unionUid, joinUserId);
            joinPlayer.notifyListener(eGamePlayerEventType.UnionRechargeUser.getValue(), args);
        }
        notifyAllMemberUnionInfo(unionUid, joinUserId);
        notifyUnionMemberCount(unionInfo);
        notifySameNicknameCount(unionInfo);
        RankMgr.changeUnionRank(unionInfo);

        try {
            //实时更新榜单上的用户的家族信息
            OreWarActivityRankMgr.changeUserInfo(joinUserId);
            //有人退出刷新下商会坑位状态，因为冠名可能会改变
            OreWarMgr.refreshOreStation();
            //跨服刷新带上用户基础信息，用来判断变化的冠名
            List<Long> userIdList = new ArrayList<>();
            userIdList.add(joinUserId);
            OreWarMgr.refreshCrossOreStation(userIdList);
            //商会战
            UnionPhaseWarMgr.unionMemberJoin(unionInfo, joinUserId);
            //走镖
            BeautyEscortMgr.unionMemberJoin(unionInfo, joinUserId);
            // [大富翁]刷新下商会加成
            DaFuWengMgr.syncDFWUserData(player);
        } catch (Exception e) {
            logger.error("addUnionMember", e);
        }
        //加入
        AutoLogMgr.add(new LogUnionMemberChange(joinUserId, "", unionUid));
        return 0;
    }

    private static void notifyUnionMemberCount(UnionInfo unionInfo) {
        if (null != unionInfo) {
            Map<Long, UnionMember> memberMap = getUnionMemberMap(unionInfo.getUnionUid());
            if (null != memberMap) {
                int memberCount = unionInfo.getMemberCount();
                for (UnionMember member : memberMap.values()) {
                    GamePlayer player = GamePlayerMgr.getOnlinePlayer(member.getUserId());
                    if (null != player) {
                        player.notifyListener(eGamePlayerEventType.UnionMemberCount.getValue(), memberCount);
                    }
                }
            }
        }
    }

    public static void updateMemberInfo(GamePlayer player, String unionUid) {
        UnionMember unionMember = getUnionMember(unionUid, player.getUserId());
        UnionInfo unionInfo = getUnionInfo(unionUid);
        boolean rankChange = false;
        UserInfo userInfo = player.getUserInfo();
        if (null != unionMember) {
            if (!Objects.equals(unionMember.getUserBaseInfo().getEarnSpeed(), userInfo.getEarnSpeed())) {
                unionMember.setUserBaseInfo(UserMgr.parseUserBaseInfo(userInfo, GameServer.getInstance().getServerId()));
                calcUnionEarnSpeed(unionInfo);
                rankChange = true;
            } else {
                unionMember.setUserBaseInfo(UserMgr.parseUserBaseInfo(userInfo, GameServer.getInstance().getServerId()));
            }
            resetMemberDailyData(unionMember);
        }

        // 修改家族当前人数
        if (null != unionInfo) {
            synchronized (unionInfo) {
                int memberCount = getUnionMemberCount(unionUid);
                if (unionInfo.getMasterUserId() == player.getUserId()) {
                    if (null != unionMember && unionMember.getPosition() != eUnionPosition.Master.getValue()) {
                        Map<Long, UnionMember> memberMap = getUnionMemberMap(unionUid);
                        if (null != memberMap) {
                            for (UnionMember tempMember : memberMap.values()) {
                                if (tempMember.getPosition() == eUnionPosition.Master.getValue()) {
                                    tempMember.setPosition(eUnionPosition.Member.getValue());
                                }
                            }
                        }
                        unionMember.setPosition(eUnionPosition.Master.getValue());
                    }
                    if (!Objects.equals(userInfo.getNickName(), unionInfo.getMasterNickName())) {
                        unionInfo.setMasterNickName(userInfo.getNickName());
                        rankChange = true;
                    }
                    if (userInfo.getVipExp() != unionInfo.getVipExp()) {
                        unionInfo.setVipExp(userInfo.getVipExp());
                        rankChange = true;
                    }
                    if (!Objects.equals(userInfo.getDecoration(), unionInfo.getDecoration())) {
                        unionInfo.setDecoration(userInfo.getDecoration());
                        rankChange = true;
                    }
                }
                if (unionInfo.getMemberCount() != memberCount) {
                    unionInfo.setMemberCount(memberCount);
                    rankChange = true;
                }
            }
        }
        if (rankChange) {
            RankMgr.changeUnionRank(unionInfo);
            UnionActivityMgr.changeUnionInfo(unionInfo);
            UnionPhaseWarMgr.unionInfoChange(unionInfo);
        }
    }

    public synchronized static void updateMemberEarnSpeed(GamePlayer player) {
        String unionUid = player.getUserInfo().getUnionUid();
        if (StringUtils.isNullOrEmpty(unionUid)) {
            return;
        }
        UnionMember unionMember = getUnionMember(unionUid, player.getUserId());
        UnionInfo unionInfo = getUnionInfo(unionUid);
        if (null != unionMember) {
            BigInteger earnSpeed = player.getModule(EarnSpeedModule.class).getEarnSpeed();
            if (!Objects.equals(unionMember.getUserBaseInfo().getEarnSpeed(), earnSpeed)) {
                unionMember.setUserBaseInfo(UserMgr.parseUserBaseInfo(player.getUserInfo(), GameServer.getInstance().getServerId()));
                calcUnionEarnSpeed(unionInfo);
                RankMgr.changeUnionRank(unionInfo);
            }
        }
    }

    /**
     * 判断会长自动转让
     */
    public static void judgeChangeUnionOwner(GamePlayer player, String unionUid) {
        UnionInfo unionInfo = UnionMgr.getUnionInfo(unionUid);
        if (null == unionInfo) {
            return;
        }
        synchronized (unionInfo) {
            UnionMember masterMember = UnionMgr.getMasterUnionMember(unionUid);
            if (null == masterMember) {
                return;
            }
            UserInfo masterUserInfo = UserMgr.getUserInfo(masterMember.getUserId());

            long offlineTime = System.currentTimeMillis() / 1000 - masterUserInfo.getLastLoginTime();
            if (offlineTime >= GameConfig.UNION_MASTER_MAX_OFFLINE_TIME * DateHelper.DAY_SECONDS) {
                UnionMember unionMember = findMasterUnionMember(unionUid, masterMember.getUserId());
                if (unionMember != null) {
                    int oldPosition = unionMember.getPosition();
                    unionMember.setPosition(eUnionPosition.Master.getValue());
                    masterMember.setPosition(eUnionPosition.Member.getValue());

                    unionInfo.setMasterUserId(unionMember.getUserId());
                    unionInfo.setMasterNickName(unionMember.getUserBaseInfo().getNickName());
                    unionInfo.setVipExp(unionMember.getUserBaseInfo().getVipExp());
                    unionInfo.setDecoration(unionMember.getUserBaseInfo().getDecoration());

                    player.sendPacket(Protocol.U_UNION_DETAIL, getUnionDetailMsg(unionUid, eUnionSyncType.Normal.getValue()));
                    UnionNoticeMgr.addNotice(null, unionUid, eUnionNoticeType.AutoChangeMaster.getValue(), unionInfo.getMasterNickName());
                    //给成员同步商会信息
                    notifyAllMemberUnionInfo(unionUid, player.getUserId());

                    //如果职位由普通变成管理，需要下发申请列表
                    if (oldPosition != eUnionPosition.Master.getValue() && oldPosition != eUnionPosition.DeputyMaster.getValue()) {
                        GamePlayer notifyPlayer = GamePlayerMgr.getOnlinePlayer(unionMember.getUserId());
                        if (null != notifyPlayer) {
                            UnionJoinApplyMgr.sendJoinApplyList(notifyPlayer, unionUid);
                        }
                    }
                    //商会冲榜
                    notifyUnionActivityMasterChange(masterMember.getUserId(), unionUid);
                    notifyUnionActivityMasterChange(unionMember.getUserId(), unionUid);
                    //变更商会信息
                    RankMgr.changeUnionRank(unionInfo);
                    UnionActivityMgr.changeUnionInfo(unionInfo);

                    AutoLogMgr.add(new LogUnionChangeMaster(unionUid, true, masterMember.getUserId(), unionMember.getUserId()));

                    //商会战活动
                    UnionPhaseWarMgr.memberPositionChange(unionInfo, masterMember.getUserId(), eUnionPosition.Member.getValue());
                    UnionPhaseWarMgr.memberPositionChange(unionInfo, unionMember.getUserId(), eUnionPosition.Master.getValue());
                    //走镖
                    BeautyEscortMgr.memberPositionChange(unionInfo, masterMember.getUserId(), eUnionPosition.Member.getValue());
                    BeautyEscortMgr.memberPositionChange(unionInfo, unionMember.getUserId(), eUnionPosition.Master.getValue());
                }
            }
        }
    }

    public static void syncUnionMemberChatMsg(String unionUid, WorldMessageProto.WorldMessageTempMsg.Builder msg) {
        Map<Long, UnionMember> memberMap = getUnionMemberMap(unionUid);
        if (null != memberMap) {
            for (UnionMember member : memberMap.values()) {
                GamePlayer player = GamePlayerMgr.getOnlinePlayer(member.getUserId());
                if (null != player) {
                    player.sendPacket(Protocol.U_WORLD_MESSAGE_SYNC, msg);
                }
            }
        }
    }

    /**
     * 通知所有成员商会信息
     * @param unionUid
     * @param excludeUserId     不通知的用户编号
     */
    private static void notifyAllMemberUnionInfo(String unionUid, long excludeUserId) {
        Map<Long, UnionMember> memberMap = getUnionMemberMap(unionUid);
        if (null != memberMap) {
            for (UnionMember member : memberMap.values()) {
                if (member.getUserId() != excludeUserId) {
                    GamePlayer player = GamePlayerMgr.getOnlinePlayer(member.getUserId());
                    if (null != player) {
                        player.sendPacket(Protocol.U_UNION_DETAIL, getUnionDetailMsg(unionUid, eUnionSyncType.Normal.getValue()));
                    }
                }
            }
        }
    }

    public static void userPatronDispatchSkillChangeNotify(String unionUid,long userId,UserPatrons userPatrons){
        if(!StringUtils.isNullOrEmpty(unionUid)) {
            UnionInfo unionInfo = UnionMgr.getUnionInfo(unionUid);
            UnionMember unionMember = UnionMgr.getUnionMember(unionUid,userId);
            if(null != unionInfo && null != unionMember && unionMember.getChamberPatronsId() == userPatrons.getPatronsId()) {
                unionMember.setChamberPatronsId(userPatrons.getPatronsId());
                unionMember.setChamberPatron(userPatrons);
                UnionMgr.notifyAllMemberChamberChange(unionUid, userId, false, userPatrons);
            }
        }
    }

    public static void notifyAllMemberChamberChange(String unionUid, long userId, boolean isRemove, UserPatrons newPatrons) {
        Map<Long, UnionMember> memberMap = getUnionMemberMap(unionUid);
        if (null != memberMap) {
            UnionProto.UnionChamberPatronsListMsg.Builder listMsg = UnionProto.UnionChamberPatronsListMsg.newBuilder();
            if (isRemove) {
                UnionProto.UnionChamberPatronsTempMsg.Builder msg = UnionPb.parseUnionChamberPatronsTempMsg(userId, isRemove, null);
                listMsg.addDataList(msg);
            } else {
                UnionProto.UnionChamberPatronsTempMsg.Builder msg = UnionPb.parseUnionChamberPatronsTempMsg(userId, isRemove, newPatrons);
                listMsg.addDataList(msg);
            }
            for (UnionMember member : memberMap.values()) {
                GamePlayer player = GamePlayerMgr.getOnlinePlayer(member.getUserId());
                if (null != player) {
                    player.getModule(EarnSpeedModule.class).scheduleAddSilver();
                    player.sendPacket(Protocol.U_UNION_CHAMBER_PATRONS_SYNC, listMsg);
                }
            }
        }
    }

    public static void resetOneDay() {
        for (UnionInfo unionInfo : unionInfoMap.values()) {
            resetUnionDailyData(unionInfo);
            Map<Long, UnionMember> memberMap = getUnionMemberMap(unionInfo.getUnionUid());
            if (null != memberMap) {
                for (UnionMember member : memberMap.values()) {
                    resetMemberDailyData(member);
                }
            }
        }
    }

    public static void resetUnionDailyData(UnionInfo unionInfo) {
        if (null == unionInfo) {
            return;
        }
        synchronized (unionInfo) {
            if (unionInfo.getModifyTime() < LocalDateTimeHelper.getZeroTimeTimeStamp() / 1000) {
                unionInfo.setConstructUserIdList(new ArrayList<>());
                unionInfo.setConstructActive(0);
                unionInfo.setDayJoinNum(0);
                unionInfo.setModifyTime(System.currentTimeMillis() / 1000);
            }
        }
    }

    public static void resetMemberDailyData(UnionMember unionMember) {
        if (null == unionMember) {
            return;
        }
        long zeroTime = LocalDateTimeHelper.getZeroTimeTimeStamp() / 1000;
        synchronized (unionMember) {
            if (unionMember.getModifyTime() < zeroTime) {
                unionMember.setModifyTime(System.currentTimeMillis() / 1000);
                unionMember.setDonateTimes(0);
                unionMember.setConstructRewardIndexList(new ArrayList<>());
                unionMember.setUnionConstructMap(new ConcurrentHashMap<>());
                unionMember.setTodayContribution(0);
            }
        }
    }

    public static UnionProto.UnionDetailMsg.Builder getUnionDetailMsg(String unionUid, int syncType) {
        UnionInfo unionInfo = getUnionInfo(unionUid);
        Map<Long, UnionMember> memberMap = getUnionMemberMap(unionUid);
        List<UnionMember> memberList = null;
        if (null != memberMap) {
            memberList = new ArrayList<>(memberMap.values());
        }
        List<UnionFlag> flagList = getUnionFlagList(unionUid);
        return UnionPb.parseUnionDetailMsg(unionUid, unionInfo, memberList, syncType, flagList);
    }

    private static List<UnionFlag> getUnionFlagList(String unionUid) {
        List<UnionFlag> list = new ArrayList<>();
        Map<Integer, UnionFlag> flagMap = unionFlagMap.get(unionUid);
        if (flagMap != null) {
            list = new ArrayList<>(flagMap.values());
        }
        return list;
    }

    public static Map<Long, UnionMember> getUnionMemberMap(String unionUid) {
        return unionMemberMap.get(unionUid);
    }

    public static int getUnionMemberCount(String unionUid) {
        Map<Long, UnionMember> memberMap = getUnionMemberMap(unionUid);
        if (null != memberMap) {
            return memberMap.size();
        }
        return 0;
    }

    public static UnionMember getUnionMember(String unionUid, long userId) {
        if (!StringUtils.isNullOrEmpty(unionUid)) {
            Map<Long, UnionMember> memberMap = getUnionMemberMap(unionUid);
            if (null != memberMap) {
                return memberMap.get(userId);
            }
            return null;
        } else {
            return deleteUnionMemberMap.get(userId);
        }
    }

    public static UnionMember getUnionMember(long userId) {
        UnionMember unionMember;
        for (Map<Long, UnionMember> memberMap : unionMemberMap.values()) {
            unionMember = memberMap.get(userId);
            if (null != unionMember) {
                return unionMember;
            }
        }
        return null;
    }

    private static UnionMember getMasterUnionMember(String unionUid) {
        UnionInfo unionInfo = getUnionInfo(unionUid);
        if (null == unionInfo) {
            return null;
        }
        Map<Long, UnionMember> memberMap = getUnionMemberMap(unionUid);
        if (null != memberMap) {
            UnionMember masterMember = memberMap.get(unionInfo.getMasterUserId());
            if (null == masterMember) {
                return null;
            }
            if (masterMember.getPosition() != eUnionPosition.Master.getValue()) {
                for (UnionMember unionMember : memberMap.values()) {
                    if (unionMember.getPosition() == eUnionPosition.Master.getValue()) {
                        unionMember.setPosition(eUnionPosition.Member.getValue());
                    }
                }
                masterMember.setPosition(eUnionPosition.Master.getValue());
            }
            return masterMember;
        }
        return null;
    }

    private static UnionMember findMasterUnionMember(String unionUid, long userId) {
        UnionMember unionMember;
        Map<Long, UnionMember> memberMap = getUnionMemberMap(unionUid);
        if (null == memberMap) {
            return null;
        }
        List<UnionMember> deputyMasterList = new ArrayList<>();
        List<UnionMember> eliteList = new ArrayList<>();
        List<UnionMember> memberList = new ArrayList<>();
        for(UnionMember member : memberMap.values()){
            if(member.getPosition() == eUnionPosition.DeputyMaster.getValue()){
                deputyMasterList.add(member);
            }else if(member.getPosition() == eUnionPosition.Elite.getValue()){
                eliteList.add(member);
            }else if(member.getPosition() == eUnionPosition.Member.getValue()){
                memberList.add(member);
            }
        }
        //先副会长
        unionMember = findNextMaster(deputyMasterList, userId);
        if(null != unionMember){
            return unionMember;
        }
        //再精英
        unionMember = findNextMaster(eliteList, userId);
        if(null != unionMember){
            return unionMember;
        }
        //最后成员
        unionMember = findNextMaster(memberList, userId);
        return unionMember;
    }

    private static UnionInfo initUnionInfo(GamePlayer player, String unionName, boolean isAllowRandomJoin, String outNotice,
                                           String wechatCode, String qqCode, String innerNotice, int unionFlag, String unionUid) {
        UserInfo userInfo = player.getUserInfo();
        long nowTime = System.currentTimeMillis() / 1000;
        UnionInfo unionInfo = new UnionInfo();
        unionInfo.setUnionUid(unionUid);
        unionInfo.setUnionName(unionName);
        unionInfo.setUnionFlag(unionFlag);
        unionInfo.setAllowRandomJoin(isAllowRandomJoin);
        unionInfo.setWechatCode(wechatCode);
        unionInfo.setQqCode(qqCode);
        unionInfo.setOutNotice(outNotice);
        unionInfo.setCreateTime(nowTime);
        unionInfo.setDelete(false);
        unionInfo.setExperience(0);
        unionInfo.setInnerNotice(innerNotice);
        unionInfo.setMasterUserId(player.getUserId());
        unionInfo.setMasterNickName(userInfo.getNickName());
        unionInfo.setVipExp(userInfo.getVipExp());
        unionInfo.setMasterJoinTime(nowTime);
        unionInfo.setMemberCount(1);
        unionInfo.setTotalEarnSpeed(BigInteger.ZERO);
        unionInfo.setConstructUserIdList(new ArrayList<>());
        unionInfo.setModifyTime(0);
        unionInfo.setWealth(0);
        unionInfo.setUnionFightRewardMark(0);
        unionInfo.setFlagModifyTime(nowTime);
        unionInfo.setUnionAliasId(getNextUnionAliasId());
        unionInfo.setDecoration(userInfo.getDecoration());
        unionInfo.setDayJoinNum(0);
        unionInfo.setApplyTitleLimit(0);
        unionInfo.setInsertOption();

        unionInfoMap.put(unionInfo.getUnionUid(), unionInfo);
        return unionInfo;
    }

    private static UnionMember createUnionMember(UnionInfo unionInfo, UserInfo userInfo, int position) {
        UnionMember unionMember = UnionMgr.getUnionMember("", userInfo.getUserId());
        if (unionMember == null) {
            unionMember = new UnionMember();
            unionMember.setUnionUid(unionInfo.getUnionUid());
            unionMember.setUserId(userInfo.getUserId());
            unionMember.setContribution(0);
            unionMember.setTotalContribution(0);
            unionMember.setDonateTimes(0);
            unionMember.setInsertOption();
        } else {
            unionMember.setUnionUid(unionInfo.getUnionUid());
            unionMember.setUserId(userInfo.getUserId());
            removeMemberFromDeleteMap(userInfo.getUserId());
            long zeroTime = LocalDateTimeHelper.getZeroTimeTimeStamp() / 1000;
            if (unionMember.getModifyTime() < zeroTime) {
                unionMember.setUnionConstructMap(new ConcurrentHashMap<>());
                unionMember.setConstructRewardIndexList(new ArrayList<>());
                unionMember.setDonateTimes(0);
            }
        }
        if (unionMember.getQuitTime() <= 0) {
            sendFirstJoinReward(userInfo);
        }
        unionMember.setNoticeReadState(eUnionNoticeReadState.Default.getValue());
        unionMember.setTodayContribution(0);
        unionMember.setTotalContribution(0);
        unionMember.setUserBaseInfo(UserMgr.parseUserBaseInfo(userInfo, GameServer.getInstance().getServerId()));
        unionMember.setPosition(position);
        unionMember.setModifyTime(System.currentTimeMillis() / 1000);

        userInfo.setUnionUid(unionInfo.getUnionUid());
        addMemberToMap(unionMember);
        calcUnionEarnSpeed(unionInfo);
        GamePlayer player = GamePlayerMgr.getOnlinePlayer(userInfo.getUserId());
        if (null != player) {
            player.notifyListener(eGamePlayerEventType.JoinUnion.getValue(), userInfo);
            player.notifyListener(eGamePlayerEventType.JoinUnionActivityCondition.getValue(), userInfo);
        } else {
            UserBussiness.updateUnionUid(userInfo.getUserId(), userInfo.getUnionUid());
        }
        memberJoinUnionActivityChange(userInfo.getUserId(), unionInfo.getUnionUid());
        UnionTradeMgr.syncRouteCanJoinToMember(unionInfo.getUnionUid(), userInfo.getUserId());   //商贸红点
        //有跨服商战则同步信息
        syncCrossTradeWarInfo(unionInfo.getUnionUid(), userInfo.getUserId());
        // 清除所有通知
        try {
            for (String unionId : StringUtils.stringToStringList(unionMember.getApplyUnionUidListString(), ",")) {
                if (!StringUtils.isNullOrEmpty(unionId)) {
                    Map<Long, UnionJoinApply> applyMap = UnionJoinApplyMgr.getUnionJoinApplyMap(unionId);
                    if (applyMap != null) {
                        UnionJoinApply unionJoinApply = applyMap.get(userInfo.getUserId());
                        if (unionJoinApply != null) {
                            applyMap.remove(userInfo.getUserId());
                            unionJoinApply.setDelete(true);
                            UnionJoinApplyMgr.syncJoinApply(unionId, unionJoinApply);
                        }
                    }
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        unionMember.setApplyUnionUidList(new ArrayList<>());
        GamePlayer applyPlayer = GamePlayerMgr.getOnlinePlayer(userInfo.getUserId());
        if (null != applyPlayer) {
            applyPlayer.getModule(UnionModule.class).syncUnionMember(unionMember);
        }
        //DataAnalyticsMgr.trackUnionJoinGuild(userInfo,unionInfo,position);
        UserMgr.addNeedUpdateToCrossMap(userInfo.getUserId(),userInfo);
        return unionMember;
    }

    /**
     * 同步跨服商战信息
     * @param unionUid
     * @param userId
     */
    public static void syncCrossTradeWarInfo(String unionUid, long userId) {
        if (TradeWarActivityMgr.unionCanCrossTradeWar(unionUid)) {//有资格参加跨服商战
            ActivityInfo activityInfo = TradeWarActivityMgr.getOpenActivityInfo();
            if (null != activityInfo) {
                GamePlayer player = GamePlayerMgr.getOnlinePlayer(userId);
                if (null != player) {
                    UserTradeWarInfo userTradeWarInfo = player.getModule(TradeWarModule.class).getUserTradeWarInfo();
                    if (null != userTradeWarInfo && userTradeWarInfo.getActivityId() != activityInfo.getActivityId()) {
                        userTradeWarInfo.setCrossScore(0);
                        userTradeWarInfo.setCrossTradeWarMoney(0);
                        userTradeWarInfo.setActivityId(activityInfo.getActivityId());
                    }
                    player.getModule(TradeWarModule.class).syncCrossUserTradeWarBattle();
                } else {
                    UserTradeWarInfo userTradeWarInfo = TradeWarMgr.getUserTradeWarInfo(userId);
                    if (null != userTradeWarInfo && userTradeWarInfo.getActivityId() != activityInfo.getActivityId()) {
                        userTradeWarInfo.setCrossScore(0);
                        userTradeWarInfo.setCrossTradeWarMoney(0);
                        userTradeWarInfo.setActivityId(activityInfo.getActivityId());
                        UserTradeWarBussiness.updateUserTradeWarInfo(userTradeWarInfo);
                    }
                }
            }
        }
    }

    public static UnionInfo getUnionInfo(String unionUid) {
        return unionInfoMap.get(unionUid);
    }

    /**
     * 搜索商会
     * @param unionAliasId
     * @return
     */
    public static UnionInfo searchUnion(long unionAliasId) {
        for (UnionInfo unionInfo : unionInfoMap.values()) {
            if (!unionInfo.isDelete() && unionInfo.getUnionAliasId() == unionAliasId) {//已删除的商会过滤
                return unionInfo;
            }
        }
        return null;
    }

    public static String getUnionName(String unionUid) {
        UnionInfo unionInfo = getUnionInfo(unionUid);
        if (unionInfo != null) {
            return unionInfo.getUnionName();
        }
        return "";
    }

    public static long getUnionAliasId(String unionUid) {
        UnionInfo unionInfo = getUnionInfo(unionUid);
        if (unionInfo != null) {
            return unionInfo.getUnionAliasId();
        }
        return 0;
    }

    private static void calcUnionEarnSpeed(UnionInfo unionInfo) {
        if (null == unionInfo) {
            return;
        }
        Map<Long, UnionMember> memberMap = getUnionMemberMap(unionInfo.getUnionUid());
        BigInteger totalEarnSpeed = BigInteger.ZERO;
        if (null != memberMap) {
            for (UnionMember unionMember : memberMap.values()) {
                totalEarnSpeed = totalEarnSpeed.add(unionMember.getUserBaseInfo().getEarnSpeed());
            }
        }
        unionInfo.setTotalEarnSpeed(totalEarnSpeed);
    }

    public static void addMemberToDeleteMap(UnionMember unionMember) {
        deleteUnionMemberMap.put(unionMember.getUserId(), unionMember);
    }

    private static void removeMemberFromDeleteMap(long userId) {
        deleteUnionMemberMap.remove(userId);
    }

    private static void addMemberToMap(UnionMember unionMember) {
        if (null == unionMember) {
            return;
        }
        if (!unionMemberMap.containsKey(unionMember.getUnionUid())) {
            unionMemberMap.put(unionMember.getUnionUid(), new ConcurrentHashMap<>());
        }
        unionMemberMap.get(unionMember.getUnionUid()).put(unionMember.getUserId(), unionMember);
    }

    private static void removeMemberFromMap(String unionUid, long userId) {
        Map<Long, UnionMember> memberMap = getUnionMemberMap(unionUid);
        if (null != memberMap) {
            memberMap.remove(userId);
        }
    }

    private static void sendFirstJoinReward(UserInfo userInfo) {
        TempServer.getTimerExecutorService().execute(() -> {
            try {
                MailManager.sendMail(userInfo.getUserId(), eMailType.SYSTEM.getValue(), PropertyHelper.parseGoodsToString(GameConfig.GAME_MONEY_INGOTS,
                        BigInteger.valueOf(GameConfig.UNION_FIRST_JOIN_REWARD)), MultipleLanguageMgr.getContent(MailManager.UNION_FIRST_JOIN_CONTENT, userInfo.getLanguage()),
                        MultipleLanguageMgr.getContent(MailManager.UNION_FIRST_JOIN_TITLE, userInfo.getLanguage()));
            } catch (Exception e) {
                logger.error(e);
            }
        });
    }

    public static boolean checkUnionNameSame(String unionName) {
        for (UnionInfo unionInfo : unionInfoMap.values()) {
            if (!unionInfo.isDelete() && Objects.equals(unionInfo.getUnionName(), unionName)) {
                return true;
            }
        }
        return false;
    }

    //仅商贸调用
    public static void addUnionExp(String unionUid, long exp, eLogMoneyType master, eLogMoneyType son) {
        UnionInfo unionInfo = UnionMgr.getUnionInfo(unionUid);
        if (null == unionInfo) {
            return;
        }
        synchronized (unionInfo) {
            long originalExp = unionInfo.getExperience();
            UnionUpgradeInfo unionUpgradeInfo = UnionConfigMgr.getUnionUpgradeInfo(unionInfo.getExperience());
            unionInfo.setExperience(unionInfo.getExperience() + exp);

            //联盟升级日志
            UnionUpgradeInfo newUnionUpgradeInfo = UnionConfigMgr.getUnionUpgradeInfo(unionInfo.getExperience());
            if (null != unionUpgradeInfo && null != newUnionUpgradeInfo) {
                if (newUnionUpgradeInfo.getLevel() > unionUpgradeInfo.getLevel()) {
                    unionLevelUp(null,unionInfo,newUnionUpgradeInfo);
                }
            }
            AutoLogMgr.add(new LogUnionExp(0L, unionUid, exp, originalExp, unionInfo.getExperience(), son.getValue()));
            try {
                List<ActivityInfo> tempList = NormalActivityMgr.getUnionRiseRankActivityList();
                List<ActivityInfo> activityInfoList = new ArrayList<>();
                for (ActivityInfo activityInfo : tempList) {
                    if ((activityInfo.getType() == eActivityType.UnionRankActivity.getValue() && activityInfo.getChildType() == 2) ||
                            (activityInfo.getType() == eActivityType.CrossUnionActivity.getValue() && activityInfo.getChildType() == 3)) {
                        activityInfoList.add(activityInfo);
                    }
                }
                if (activityInfoList.size() == 0) {
                    return;
                }
                if (activityInfoList.size() > 1) {
                    logger.error("one more union rank activity exist.");
                }
                ActivityInfo activityInfo = activityInfoList.get(0);
                int activityId = activityInfo.getActivityId();
                if (unionInfo.getRankActivityId() != activityId) {
                    unionInfo.setRankActivityId(activityId);
                    unionInfo.setRankAddExp(0L);
                }
                unionInfo.setRankAddExp(unionInfo.getRankAddExp() + exp);
                UnionActivityMgr.addUnionActivityValue(activityId, unionUid, unionInfo.getRankAddExp()); //排行
            } catch (Exception e) {
                logger.error(e);
            }
        }
    }

    public static void addUnionExp(GamePlayer player, String unionUid, long exp, eLogMoneyType master, eLogMoneyType son) {
        UnionInfo unionInfo = UnionMgr.getUnionInfo(unionUid);
        if (null == unionInfo) {
            return;
        }
        synchronized (unionInfo) {
            long originalExp = unionInfo.getExperience();
            UnionUpgradeInfo unionUpgradeInfo = UnionConfigMgr.getUnionUpgradeInfo(unionInfo.getExperience());
            unionInfo.setExperience(unionInfo.getExperience() + exp);

            player.notifyListener(eGamePlayerEventType.UnionExpRiseRank.getValue(), new UnionRiseRankArgs(UnionRiseRankArgs.NOTIFY_TYPE_NORMAL, BigInteger.valueOf(exp), unionUid));
            // 同步联盟信息
            player.sendPacket(Protocol.U_UNION_DETAIL, getUnionDetailMsg(unionUid, eUnionSyncType.Normal.getValue()));

            //联盟升级日志
            UnionUpgradeInfo newUnionUpgradeInfo = UnionConfigMgr.getUnionUpgradeInfo(unionInfo.getExperience());
            if (null != unionUpgradeInfo && null != newUnionUpgradeInfo) {
                if (newUnionUpgradeInfo.getLevel() > unionUpgradeInfo.getLevel()) {
                    unionLevelUp(player,unionInfo,newUnionUpgradeInfo);
                }
            }
            AutoLogMgr.add(new LogUnionExp(player.getUserId(), unionUid, exp, originalExp, unionInfo.getExperience(), son.getValue()));
        }
    }

    /**
     * 联盟升级
     */
    public static void unionLevelUp(GamePlayer player,UnionInfo unionInfo, UnionUpgradeInfo newUnionUpgradeInfo){
        RankMgr.changeUnionRank(unionInfo);
        UnionNoticeMgr.addNotice(player, unionInfo.getUnionUid(), eUnionNoticeType.UnionUpgrade.getValue(), String.valueOf(newUnionUpgradeInfo.getLevel()));
        DragonBoatRaceMgr.unionLevelUp(unionInfo.getUnionUid());
        //商会升级
        BeautyEscortMgr.upgradeUnion(unionInfo);
    }

    public static void addUnionWealth(GamePlayer player, String unionUid, long wealth, eLogMoneyType master, eLogMoneyType son) {
        UnionInfo unionInfo = UnionMgr.getUnionInfo(unionUid);
        if (null == unionInfo) {
            return;
        }
        synchronized (unionInfo) {
            long originalWealth = unionInfo.getWealth();
            unionInfo.setWealth(unionInfo.getWealth() + wealth);
            // 同步联盟信息
            player.sendPacket(Protocol.U_UNION_DETAIL, getUnionDetailMsg(unionUid, eUnionSyncType.Normal.getValue()));
            AutoLogMgr.add(new LogUnionWealth(player.getUserId(), unionUid, true, wealth, originalWealth, unionInfo.getWealth(), son.getValue()));
        }
    }

    public static long removeUnionWealth(GamePlayer player, String unionUid, long wealth, eLogMoneyType master, eLogMoneyType son) {
        UnionInfo unionInfo = UnionMgr.getUnionInfo(unionUid);
        if (null == unionInfo) {
            return 0;
        }
        synchronized (unionInfo) {
            if (unionInfo.getWealth() - wealth < 0) {
                return 0;
            } else {
                long originalWealth = unionInfo.getWealth();
                unionInfo.setWealth(unionInfo.getWealth() - wealth);
                player.sendPacket(Protocol.U_UNION_DETAIL, getUnionDetailMsg(unionUid, eUnionSyncType.Normal.getValue()));
                AutoLogMgr.add(new LogUnionWealth(player.getUserId(), unionUid, false, wealth, originalWealth, unionInfo.getWealth(), son.getValue()));
                return wealth;
            }
        }
    }

    public static int getSameNicknameCount(UnionInfo unionInfo) {
        int count = 0;
        UnionMember master = getMasterUnionMember(unionInfo.getUnionUid());
        String masterNickName = master.getUserBaseInfo().getNickName().trim();
        String startName = masterNickName.substring(0, 2);
        String endName = masterNickName.substring(masterNickName.length() - 2, masterNickName.length());
        Map<Long, UnionMember> unionMemberMap = getUnionMemberMap(unionInfo.getUnionUid());
        for (UnionMember member : unionMemberMap.values()) {
//            if(member.getPosition() != eUnionPosition.Master.getValue()){
            if (member.getUserBaseInfo().getNickName().trim().indexOf(startName) >= 0 || member.getUserBaseInfo().getNickName().trim().indexOf(endName) >= 0) {
                count++;
            }
//            }
        }
        return count;
    }

    public static void notifySameNicknameCount(UnionInfo unionInfo) {
        if (null != unionInfo) {
            Map<Long, UnionMember> memberMap = getUnionMemberMap(unionInfo.getUnionUid());
            if (null != memberMap) {
                int memberCount = getSameNicknameCount(unionInfo);
                for (UnionMember member : memberMap.values()) {
                    GamePlayer player = GamePlayerMgr.getOnlinePlayer(member.getUserId());
                    if (null != player) {
                        player.notifyListener(eGamePlayerEventType.UnionSameNickname.getValue(), memberCount);
                    }
                }
            }
        }
    }

    public static boolean isSameUnion(long userId1, long userId2) {
        UserInfo userInfo1 = UserMgr.getUserInfo(userId1);
        UserInfo userInfo2 = UserMgr.getUserInfo(userId2);
        if (userInfo1 != null && userInfo2 != null) {
            if (!StringUtils.isNullOrEmpty(userInfo1.getUnionUid()) && userInfo1.getUnionUid().equals(userInfo2.getUnionUid())) {
                return true;
            }
        }
        return false;
    }

    /**
     * 获得新的会旗
     *
     * @param unionId
     * @param flagId
     */
    public static void addUnionFlag(String unionId, int flagId) {
        UnionInfo unionInfo = getUnionInfo(unionId);
        if (unionInfo == null || unionInfo.isDelete()) {
            return;
        }
        synchronized (unionFlagMap) {
            Map<Integer, UnionFlag> flagMap = unionFlagMap.get(unionId);
            if (flagMap == null) {
                flagMap = new ConcurrentHashMap<>();
                unionFlagMap.put(unionId, flagMap);
            }
            UnionFlag flag = flagMap.get(flagId);
            if (flag == null) {
                flag = new UnionFlag();
                flag.setUnionUid(unionId);
                flag.setFlagId(flagId);
                flag.setInsertOption();
                flagMap.put(flagId, flag);
            }
            if (isFlagExpired(flag)) {
                flag.setExpireTime(System.currentTimeMillis() + GoodsMgr.getUnionFlagDurationTime(flagId));
                flag.setRead(false);
            } else {
                flag.setExpireTime(flag.getExpireTime() + GoodsMgr.getUnionFlagDurationTime(flagId));
            }
        }
    }

    public static boolean hasUnionFlag(String unionId, int flagId) {
        boolean hasFlag = ConfigMgr.hasUnionFlag(flagId);
        if (hasFlag) {
            return true;
        }
        Map<Integer, UnionFlag> flagMap = unionFlagMap.get(unionId);
        if (flagMap == null) {
            return false;
        }
        UnionFlag flag = flagMap.get(flagId);
        if (flag == null) {
            return false;
        }
        if (isFlagExpired(flag)) return false;
        return true;
    }

    /**
     * 会旗是否过期
     *
     * @param flag
     * @return
     */
    private static boolean isFlagExpired(UnionFlag flag) {
        if (System.currentTimeMillis() > flag.getExpireTime()) {
            return true;
        }
        return false;
    }

    public static void checkUnionFlag() {
        for (Map.Entry<String, Map<Integer, UnionFlag>> entry : new HashMap<>(unionFlagMap).entrySet()) {
            String unionId = entry.getKey();
            UnionInfo unionInfo = getUnionInfo(unionId);
            if (unionInfo == null) {
                continue;
            }
            int curFlagId = unionInfo.getUnionFlag();
            for (UnionFlag flag : new ArrayList<>(entry.getValue().values())) {
                if (flag.getFlagId() == curFlagId && isFlagExpired(flag)) {
                    //如果是当前的会旗，并且过期了,设置为默认会旗
                    int preUnionFlag = unionInfo.getPreUnionFlag();
                    unionInfo.setUnionFlag(preUnionFlag);
                    logger.info("unionFlag {} expired, change to {}", curFlagId, preUnionFlag);
                    //增加联盟日志
                    UnionNoticeMgr.addNotice(null, unionId, eUnionNoticeType.UnionModify.getValue(), "");
                    RankMgr.changeUnionRank(unionInfo);
                    UnionActivityMgr.changeUnionInfo(unionInfo);
                }
            }
        }
    }

    public static int getUnionMaxMemberSize(String unionUid) {
        UnionInfo unionInfo = getUnionInfo(unionUid);
        if (unionInfo == null) {
            return 0;
        }
        return UnionConfigMgr.getMaxMemberCount(unionInfo.getExperience());
    }

    /**
     * 查找符合条件的会长人选
     * @param memberList
     * @param oldMasterUserId
     * @return
     */
    private static UnionMember findNextMaster(List<UnionMember> memberList, long oldMasterUserId){
        UnionMember unionMember = null;
        for (UnionMember member : memberList) {
            if (member.getUserId() != oldMasterUserId) {
                long offlineTime = System.currentTimeMillis() / 1000 - UserMgr.getLastLoginTime(member.getUserId());
                if (offlineTime < GameConfig.UNION_MASTER_MAX_OFFLINE_TIME * DateHelper.DAY_SECONDS) {
                    if (unionMember == null) {
                        unionMember = member;
                    } else if (member.getTotalContribution() > unionMember.getTotalContribution()) {
                        unionMember = member;
                    }
                }
            }
        }
        return unionMember;
    }
    public static Map<String, Map<Long, UnionMember>> getUnionMemberMap() {
        return unionMemberMap;
    }

    /**
     * 一键领取建设宝箱奖励
     */
    public static AssistantProto.AssistantCommonResult.Builder oneKeyReceiveUnionConstructActiveReward(GamePlayer player){
        AssistantProto.AssistantCommonResult.Builder builder = AssistantProto.AssistantCommonResult.newBuilder();
        String unionUid = player.getUserInfo().getUnionUid();
        UnionInfo unionInfo = UnionMgr.getUnionInfo(unionUid);
        if(null == unionInfo){
            builder.setRet(GameErrorCode.E_UNION_NO_JOIN_UNION);
            return builder;
        }
        UnionMember unionMember = UnionMgr.getUnionMember(unionUid, player.getUserId());
        if(null == unionMember){
            builder.setRet(GameErrorCode.E_UNION_NO_JOIN_UNION);
            return builder;
        }
        Property reward = new Property();
        boolean flag = false;
        for(Integer constructActive : ConfigMgr.getUnionConstructActiveList()){
            int index = ConfigMgr.getUnionConstructActiveIndex(constructActive);
            if (-1 == index) {
                continue;
            }
            if(isCanRewardConstruct(unionInfo,unionMember,constructActive) != 0){
                continue;
            }
            unionMember.addConstructRewardIndex(constructActive);
            reward.addProperty(ConfigMgr.getUnionConstructActiveReward(index));
            flag = true;
        }
        if(!flag){
            builder.setRet(GameErrorCode.E_UNION_CONSTRUCT_ACTIVE_NO_ENOUGH);
            return builder;
        }
        if (reward.getGoods().size() > 0) {
            player.getModule(CurrencyModule.class).addCurrency(reward, eLogMoneyType.Union, eLogMoneyType.UnionConstructActive);
            builder.setReward(PropertyHelper.parsePropertyToString(reward));
        }
        player.sendPacket(Protocol.U_UNION_DETAIL, UnionMgr.getUnionDetailMsg(unionUid, eUnionSyncType.Normal.getValue()));
        builder.setRet(0);
        return builder;
    }

    public static int isCanRewardConstruct(UnionInfo unionInfo, UnionMember unionMember,int constructActive){
        if (unionMember.hasConstructRewardIndex(constructActive)) {
            return GameErrorCode.E_UNION_HAS_GET_CONSTRUCT_ACTIVE_REWARD;
        }
        if (unionInfo.getConstructActive() < constructActive) {
            return GameErrorCode.E_UNION_CONSTRUCT_ACTIVE_NO_ENOUGH;
        }
        return 0;
    }




    /**
     * 获取议事厅门客总赚速
     * @param unionInfo
     * @return
     */
    public static long getChamberPatronsTotalEarnSpeed(UnionInfo unionInfo){
        long totalEarnSpeed = 0;
        if(unionInfo == null){
            return totalEarnSpeed;
        }
        Map<Long, UnionMember> unionMemberMap = getUnionMemberMap(unionInfo.getUnionUid());
        if(unionMemberMap == null){
            return totalEarnSpeed;
        }
        for(UnionMember item : unionMemberMap.values()){
            if(item.getChamberPatron() != null){
                totalEarnSpeed += item.getChamberPatron().getAbility().longValue();
            }
        }
        return totalEarnSpeed;
    }

}
